问题描述
void change(float amount, int &d2, int &d1, int &c50, int &c20, int &c10, int &c5)
{
int dollars = amount;
d2 = dollars / 2;
d1 = dollars % 2;
int cents = (amount - dollars) * 100; // here's probably the prob
c50 = cents / 50;
c20 = cents % 50 / 20;
c10 = cents % 50 % 20 / 10;
c5 = cents % 50 % 20 % 10 / 5;
}
如果amount = 79.85
,c5
最终将等于0.
我认为问题可能出在变量cents的赋值上.
谁能解决这个问题?
预先感谢.
If the amount = 79.85
, c5
will be finally equal to 0.
I reckon the problem is probably about the assignment of the variable cents.
Can anyone solve this problem?
Thanks in advance.
推荐答案
int cents = (amount - dollars) * 100; // here''s probably the prob
并且您的评论是正确的.发生的事情是(金额-美元)是一个浮点运算(与上面的注释之一相反),并提供0.849998或类似的值.这是由于以下事实:浮点表示不能正确存储所有有理数.相反,它使用可以由底数2的尾数表示的最接近的近似值.
在下一步中,将值乘以100(这也被强制为浮点数),您将得到:84.9998,然后通过强制转换为int将其截断为84.
那么出了什么问题呢?您不应该将值强制转换为int,而将四舍五入转换为int.这是一种实现方法:
and you were correct in your comment. What happens is that (amount - dollars) is a floating point operation (contrary what one of the comments above said) and delivers a value of 0.849998 or something the like. This is due to the fact that the floating point representation cannot correctly store all rational numbers. Instead it uses the nearest approximation that can be represented by a mantissa to the base 2.
In the next step that value is multiplied by 100 (which is also forced up to floating point) and you get: 84.9998, which is then truncated to 84 by the cast to int.
So what went wrong? You should not have cast the value to int but rounded it to int. Here is a way to do that:
double centsDlb = (amount - dollars) * 100.0;
int cents = floor (centsDlb + 0.5);
当然,您可以将两行代码压缩为一个代码.
Pablo提供的解决方案也可以帮助您,但请想象一下,如果有人指定79.849作为输入会发生什么.这就是为什么要使用舍入的原因.
使用floor函数时,请不要忘记包含"math.h".
而且,您可能想检查一下,如果有人向您的函数输入了负数,该怎么办.
希望对您有所帮助.
Of course you can contract both lines of code to a single one.
The solution given by Pablo will also get you there, but imagine what happens if someone specifies 79.849 as input. That''s why you want to use rounding.
Don''t forget to include "math.h" when you use the floor function.
And you might want to check what happens if someone enters a negative amount to your function.
Hope that helps.
int cents = (amount + 0.00001 - dollars) * 100.0;
希望这会有所帮助,
Pablo.
Hope this helps,
Pablo.
这篇关于有关float类型精度的一些问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!