|
///都是一些细节的错误,太可惜了。程序修正如下:
#include <iomanip> ///输出输入流的格式设置
#include<iostream>
using namespace std;
class stock ///库存类
{
private:
char company[30];
int shares; ///数量
double share_val; // 单价
double total_val; ///总价格
void set_tot (){total_val = shares * share_val;} ///求总价格的函数
public:
void acquire (const char * co,int n,double pr); ///需求
void buy (int num ,double price); //买
void sell(int num ,double price); //卖
void update (double price);
void show(); //显示
};
void stock::acquire(const char * co,int n,double pr) ///需求
{
strncpy(company,co,29);
company [29] = '\0';
if(n<0)
{
cerr << "numble of shares can't be negative:"
<<"shares set to 0.\n";
shares = 0;
}
else shares =n; ///数量
share_val =pr; ///价格
set_tot(); ///求出总价格
}
void stock:: buy (int num,double price)
{
if (num<0)
{
cerr<<"number of shares purchaseed can't be negative."
<<"Transaction is aborted.\n";
}
else{
shares += num; ///原来的数量加上num等于现在的数量
share_val = price; /// 新价格
set_tot (); ///求出新的总价格
}
}
void stock:: sell (int num,double price)
{
if (num<0)
{
cerr<< "number of shares sold can't be negative."
<<"Transaction is aborted.\n";
}
else if (num > shares)
{
cerr<<"You can't sell more than you have !"
<<"Thansaction is aborted.\n";
}
else
{
shares -=num;
share_val = price;
set_tot();
}
}
void stock:: update (double price)
{
share_val = price;
set_tot();
}
void stock::show()
{
cout<<"company:"<<company<<" "
<<"shares:"<<shares<<'\n'
<<"share price: $"<<share_val<<" "
<<"total worth:$"<<total_val<<'\n';
cout<<endl;
}
int main()
{
stock stock1;
stock1.acquire("nanosmart",20,12.50);
cout<<setiosflags(ios_base::fixed); ///输出流的格式设置
cout.precision(2);
cout<<setiosflags(ios_base::showpoint); ///输出流的格式设置
stock1.show();
stock1.buy(15,18.25);
stock1.show();
stock1.sell(8,20.00);
stock1.show();
return 0;
}
///我只做了一些小的修改,注释是根据自己的理解做的,不知对不对~! |
|