C++ 为什么我的金额是四舍五入的?
我有以下分配资金的代码。美元钞票总是对的,它总是以女巫给我的找零错误而告终。我尝试了C++ 为什么我的金额是四舍五入的?,c++,if-statement,C++,If Statement,我有以下分配资金的代码。美元钞票总是对的,它总是以女巫给我的找零错误而告终。我尝试了setprecision()和ceil,但它只起到了一定的作用。我不知道如何修复此代码 #include <iostream> #include <stdlib.h> #include <math.h> using namespace std; int main () { double amount; int twenty, five, one, half_
setprecision()
和ceil
,但它只起到了一定的作用。我不知道如何修复此代码
#include <iostream>
#include <stdlib.h>
#include <math.h>
using namespace std;
int main ()
{
double amount;
int twenty, five, one, half_dollar, quarter, dime, nickel, penny;
cout <<"Please enter amount: ";
cin >> amount;
cout <<"You will need ";
if (amount >= 20)
{
twenty = (amount/20);
amount = (amount-(20*twenty));
if (twenty > 0)
{
cout << twenty << " $20 bill(s). ";
}
}
if (amount >= 5 )
{
five = (amount/5);
amount = (amount-(5*five));
if (five > 0)
{
cout << five << " $5 bill(s). ";
}
}
if (amount >= 1 )
{
one = (amount/1);
amount = (amount-(1*one));
if (one > 0)
{
cout << one << " $1 bill(s). ";
}
}
if (amount >= 0.50)
{
half_dollar = (amount/0.50);
amount = (amount-(0.50*half_dollar));
if (half_dollar > 0)
{
cout << half_dollar << " 50c coin(s). ";
}
}
if (amount >= 0.25 )
{
quarter = (amount/0.25);
amount = (amount-(0.25*quarter));
if (quarter > 0)
{
cout << quarter << " 25c coin(s). ";
}
}
if (amount >= 0.10 )
{
dime = (amount/0.10);
amount = (amount-(0.10*dime));
if (dime > 0)
{
cout << dime << " 10c coin(s). ";
}
}
if (amount >= 0.05 )
{
nickel = (amount/0.05);
amount = (amount-(0.05*nickel));
if (nickel > 0)
{
cout << nickel << " 5c coin(s). ";
}
}
if (amount >= 0.01)
{
penny = (amount/0.01);
amount = (amount-(0.01*penny));
if (penny > 0)
{
cout << penny << " 1c coin(s).\n";
}
}
system("pause");
return 0;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
双倍金额;
二十,五,一,半美元,四分之一,一角,五分,一便士;
金额;
cout(0)
{
cout(0)
{
cout(0)
{
cout(0)
{
cout(0)
{
cout(0)
{
cout(0)
{
cout(0)
{
cout当输出半美元的数字时,实际上是在写“一”的值
if(半美元>0){
永远,永远,永远,永远,永远,把钱(或任何需要精确计数的东西)存储为浮点
或双精度
int
或long
是一条路要走。欢迎来到数字稳定性的奇妙世界和浮点表示的局限性(尤其是32位的浮点
,而不是64位的双精度
)。举个有趣的例子,0.1
在float
或double
中实际上都不是一个数字,这意味着用它进行的任何计算结果都可能不会像您预期的那样。在货币计算中,避免使用浮点,您可以使用整数,而不是使用长双精度,并祈祷:D严肃点,您需要一个小数或者至少是一个固定点类型。使用长的长度并考虑最后4个数字作为分数(那么你必须用乘法运算来做一些魔术)。这是一个很好的正确示例。谢谢,我刚刚纠正了这一点。我仍然得到一便士或25%的值。在某个点上,您需要使用除just>以外的其他方法进行比较。例如,如果输入的金额为0.01,代码将进入最后一次比较金额>0.01
,并且由于0.01不大于0.01,c条件代码不会运行。这也是为什么每个人都建议不要在货币计算中使用浮点类型的原因。如果必须这样做,一种常见的方法是将两个数字的绝对差与公差进行比较-If(abs(amount-0.01)<0.0001){
而不是If(amount>0.01){
if (half_dollar > 0){
cout << one << " 50c coin(s). ";