为什么 (int)(33.46639 * 1000000) 返回 33466389?
(int)(33.46639 * 1000000)
返回 33466389
为什么会发生这种情况?
(int)(33.46639 * 1000000)
returns 33466389
Why does this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
浮点数学并不完美。 每个程序员都应该了解的内容。
Floating point math isn't perfect. What every programmer should know about it.
双精度并不精确,因此内部 33.46639 实际上存储为 33.466389
编辑:正如理查德所说,它是浮点数据(以二进制形式存储在有限的位集中),所以它不完全是这样)...
Double precision is not exact, so internally 33.46639 is actually stored as 33.466389
Edit: As Richard said, it's floating point data, (stored in binary in a finite set of bits) so it's not exactly that) ....
那是 1994 年底的除夕夜。英特尔首席执行官安迪·格罗夫 (Andy Grove) 度过了美好的一年,奔腾处理器问世并大受欢迎。于是,他走进一家酒吧,点了一杯双份尊尼获加绿牌威士忌。
调酒师把酒端上来,说道:“先生,20 美元。”
格罗夫把一张二十美元的钞票放在柜台上,看了一会儿,说道:“零钱留着吧。”
http://en.wikipedia.org/wiki/Pentium_FDIV_bug
It was New Years' Eve at the end of 1994. Andy Grove, CEO of Intel, was coming off a great year, what with the Pentium processor coming out and being a big hit. So, he walked into a bar and ordered a double shot of Johnnie Walker Green Label.
The bartender served it up and said, "that will be $20, sir."
Grove put a twenty dollar bill on the counter, looked at it for a moment, and said, "keep the change."
http://en.wikipedia.org/wiki/Pentium_FDIV_bug
原因是 33.46639 将表示为略小于该数字的值。
乘以 1000000 将得到 33466389.99999999。
使用 (int) 进行类型转换将仅返回整数部分 (33466389)。
如果您想要“正确”的数字,请在类型转换之前尝试 round() 。
The reason is that 33.46639 will be represented as something slightly less than that number.
Multiplying by 1000000 will give you 33466389.99999999.
Type-casting using (int) will then just return the integer part (33466389).
If you want the "right" number, try round() before type casting.
如果你问为什么它没有变成
33466390
,那是因为double
没有无限精度,并且数字无法用二进制精确表达。如果将
double
替换为decimal
((int)(33.46639m * 1000000)
),则等于33466390< /code>,因为
小数
是以 10 为基数计算的。If you're asking why it doesn't become
33466390
, it's becausedouble
s do not have infinite precision, and the number cannot be expressed exactly in binary.If you replace the
double
with adecimal
((int)(33.46639m * 1000000)
), it be equal to33466390
, becausedecimal
s are calculated in base 10.因为33.46639无法用有限个二进制数字精确表示。 33.46639 * 1000000的实际结果是33466389.9999999962747097015380859375。转换会将其截断为 33466389。
Because 33.46639 can't be expressed exactly in a finite number of binary digits. The actual result of 33.46639 * 1000000 is 33466389.9999999962747097015380859375. The cast truncates it to 33466389.
您得到不同结果的原因是您使用“cast”
将结果转换为“int”类型...在相乘时将整数类型向上或向下舍入然后转换为“int”......不要依赖浮点来足够准确......Skeet 在他的网站上发布了精彩的介绍 此处 和 此处...
The reason you got a different result is the fact that you used a 'cast'
to cast the result to a type of 'int'... which either rounded up or down the integral type when multipled together and then converted to 'int'.... do not rely on floating point to be accurate enough....Skeet posted an excellent introduction on his site here and here...