我想知道为什么我的代码不以美分显示金额,而是以美元显示金额。有人看到我要去哪里了吗?
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;
}
最佳答案
进行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
作为输出。对于更严格的财务计算,使用带有舍入误差的浮点类型会遇到很多困难,但是我怀疑在您的情况下这没什么大不了的。
关于c++ - 硬币的输入量和美元和美分的输出量,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52374939/