“为了”循环增量无法正常工作。为什么?
for (float i = -1; i <= 1; i+=0.1f)
{
Console.WriteLine(i);
}
这是结果
-1
-0.9
-0.8
-0.6999999
-0.5999999
-0.4999999
-0.3999999
-0.2999999
-0.1999999
-0.09999993
7.450581E-08
0.1000001
0.2000001
0.3000001
0.4000001
0.5000001
0.6000001
0.7000001
0.8000001
0.9000002
for (float i = -1; i <= 1; i+=0.1f)
{
Console.WriteLine(i);
}
This is results
-1
-0.9
-0.8
-0.6999999
-0.5999999
-0.4999999
-0.3999999
-0.2999999
-0.1999999
-0.09999993
7.450581E-08
0.1000001
0.2000001
0.3000001
0.4000001
0.5000001
0.6000001
0.7000001
0.8000001
0.9000002
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
Float 和 Double 无法精确显示十进制值。看看维基百科它们是如何实现的。
您可能想使用
Decimal
来代替。Float and double are not able to display decimal values exactly. Have a look at wikipedia how they're implemented.
You may want to use
Decimal
instead.您需要阅读以下内容:
每个计算机科学家需要了解的内容关于浮点数
You need to read this:
What Every Computer Scientist Needs To Know About Floating Point Numbers
使用整数进行索引。如果您需要循环内的浮点值,请在那里计算:
Use integer numbers for indexing purposes. And if you need float values inside the loop, calculate it there:
float
表示 32 位 浮点数。它不能准确地表示这些值。这是另一篇关于 .NET 浮点的必读文章:http://csharpindepth .com/Articles/General/FloatingPoint.aspxfloat
represents a 32-bit floating point number. It cannot accurately represent these values. Here is another, must-read-article, about floating point specifically for .NET: http://csharpindepth.com/Articles/General/FloatingPoint.aspx这是因为您使用的是浮点。浮点数的计算并不完全正确,因为您的计算机内部使用二进制数而不是十进制数。有关该问题的详细信息如下:http://floating-point-gui.de/
This is because of you're using floating points. Calculating of floating points is not totally correct, because your computer is using binary numbers internally and not decimal numbers. Good information about that problem are here: http://floating-point-gui.de/
因为浮点数不是精确的十进制数,而是浮点数。请改用十进制。
请参阅维基百科以供参考:维基百科
Because a float is not an exact decimal number but a floating point number. Use decimal instead.
See wikipedia for reference: Wikipedia