硬币的输入量和美元和美分的输出量

时间:2018-09-17 20:04:06

标签: c++

我想知道为什么我的代码没有以美分显示金额,而仅以美元显示金额。有人看到我要去哪里了吗?

int dollars;
int change;
int quarters;
int dimes;
int nickels;
int pennies;

cout << "Enter amount of quaters" << endl;
cin >> quarters;

cout << "Enter amount of dimes" << endl;
cin >> dimes;

cout << "Enter amount of nickels" << endl;
cin >> nickels;

cout << "Enter amount of pennies" << endl;
cin >> pennies;

quarters = quarters * 0.25;
dimes = dimes * 0.10;
nickels = nickels * 0.05;
pennies = pennies * 0.01;

dollars = quarters + dimes + nickels + pennies;
change = dollars % quarters + dimes + nickels + pennies;

cout << "You have " << dollars << " dollar(s)" << endl;
cout << "You have " << change << " cents" << endl;

return 0;

}

1 个答案:

答案 0 :(得分:2)

dimes = dimes * 0.10;dimes仍然是int,不能代表小数。您将需要将它们存储在float中。

这是一个例子:

int dimes_int = 2;
float dimes_float = dimes_int * 0.1;
dimes_int = dimes_float;//convert the floating point number to an integer.

std::cout << dimes_float << ' ' << dimes_int << '\n';

您应该获得0.2 0作为输出。

对于更严肃的财务计算,使用带有舍入错误的浮点类型会遇到很多困难,但是我怀疑在您的情况下这没什么大不了的。