我不太清楚我的代碼在哪裏導致導致錯誤計算的問題。當我運行該程序時出現以下警告:爲什麼我的計算在我的程序中搞砸了?
C4305:'argument':從'double'截斷爲'float'。
似乎是壞了稅額(TA)和總成本(TC),
Current Output:
Cost before Tax: $30.20
Tax Amount: $30.20
Total Cost: $-107374144.00
ground beef is ex-sponged
Press any key to continue . .
What it **should** be:
Your item name:ground beef
Cost before Tax: $30.20
Tax Amount: $2.64
Total Cost: $32.84
ground beef is ex-sponged
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<iomanip>
#include<string>
using namespace std;
class item
{
public:
item(char* = " " ,float=0.0,int=0,float=0.0);
~item();
void print();
void calc(int);
private:
char name[20];
int quan;
float cost, tp, cbt, tax, tc;
};
item::~item()
{
cout << name << " is ex-sponged"<<endl;
system("pause");
}
item::item(char *w,float x, int y, float z)
{
strcpy(name, w);
cost = x;
quan=y;
tp = z;
tax=cost*quan;
tc=cbt+tax;
cbt = cost*quan;
}
void item::print()
{
cout << "Your item name:" << name << endl;
cout << "Cost before Tax: $" << cbt << endl;
cout << "Tax Amount: $" << tax << endl;
cout << "Total Cost: $" << tc << endl;
}
void item::calc(int n)
{
quan += n;
cbt = cost*quan;
tax = cbt*tp/100;
tc = cbt + tax;
}
int main()
{
item i("ground beef", 7.55, 4, 8.75);
cout << setprecision(2) << showpoint << fixed;
i.print();
}
最大的錯誤是你使用浮點數來表示錢。 – user2079303 2014-10-30 14:57:10
前海綿被拼寫刪除,雖然我喜歡你的版本更好。 – interjay 2014-10-30 14:59:04
另外,在這裏使用C字符串沒有什麼好的理由(畢竟你使用'cout')。使用C++'std :: string'。 – 2014-10-30 15:01:31