本文介绍了如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Java中遇到以下问题 - 我需要在0.1f和1.0之间迭代f以0.1f为增量,所以我希望我的输出看起来像这样:
I am having a following problem in Java - I need to iterate between 0.1f and 1.0f in 0.1f increments,so I would like my output to look like this:
0.1
0.2
0.3
0.4
...
0.9
相反,当我这样做时:
for(float i = 0.1f; i < 1f; i += 0.1f)
System.out.println(i);
我得到
0.1
0.2
0.3
0.4
0.5
0.6
0.70000005
0.8000001
0.9000001
我想它与计算机表示分数的方式有关,但我想知道为什么是这个,如果我有什么办法可以阻止它。
谢谢。
I imagine it has something to do with the way fractions are represented by a computer,but I would like to know why is this,and if there is anything I can do to stop it.thanks.
推荐答案
在for循环中使用整数以避免重复的浮点数学运算,这会导致浮点错误。
Use integers in your for loop to avoid repeated floating point math, which compounds floating-point errors.
for (int i = 1; i < 10; i++)
{
float f = (float) i / 10.0f;
System.err.println(f);
}
这篇关于如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!