将浮点数除以 10
可能的重复:
为什么十进制数不能用二进制精确表示?
我正在开发一个非常简单的算法,用于在 C++ 下使用数学。
我有一个名为“step”的浮点变量,每次完成 while 循环时,我都需要将 step 除以 10。
所以我的代码有点像这样,
float step = 1;
while ( ... ){
//the codes
step /= 10;
}
在我愚蠢的简单逻辑中,结果很好。步骤将除以 10,从 1 到 0.1,从 0.1 到 0.01。
但事实并非如此,而是出现了类似 0.100000000001 的内容。我当时就想“到底是什么”
有人能帮我解决这个问题吗?这可能是我不完全理解的数据类型本身的问题。因此,如果有人可以进一步解释,我们将不胜感激。
Possible Duplicate:
Why can't decimal numbers be represented exactly in binary?
I am developing a pretty simple algorithm for mathematics use under C++.
And I have a floating point variable named "step", each time I finish a while loop, I need step to be divided by 10.
So my code is kind of like this,
float step = 1;
while ( ... ){
//the codes
step /= 10;
}
In my stupid simple logic, that ends of well. step will be divided by 10, from 1 to 0.1, from 0.1 to 0.01.
But it didn't, instead something like 0.100000000001 appears. And I was like "What The Hell"
Can someone please help me with this. It's probably something about the data type itself that I don't fully understand. So if someone could explain further, it'll be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个数字问题。问题是 1/10 是一个无限长的二进制数,连续除以 10 会导致每一步的误差相加。为了获得更稳定的版本,您应该乘以除数。但请注意:结果也不准确!您可能需要将浮点型替换为双精度型以最小化错误。
It is a numerical issue. The Problem is that 1/10 is a endless long number in binary and the successive apply of a division by 10 ends up with summing the error in each step. To get a more stable version you should multiply the divisor. But take care: the result is also not exact! You may want to replace the float with a double to minimize the error.
对于二进制浮点算术来说,除以 1 不能精确,因此您看到的结果与您的预期有点不同。
二进制浮点表示为整数比,其中分母是 2 的幂。由于不存在完全等于十分之一的二进制分数,因此您将看到最接近的可表示数字,而不是您期望的数字。
The division by ten cannot be exact for binary floating point arithmetic, so you see results that will look a little bit off from what you expect.
Binary floating are represented as an integer ratio where the denominator is a power of two. Since there in no binary fraction exactly equal to one-tenth, you'll see the nearest representable number instead of the one you expected.