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
Instead,when I do:
for(float i = 0.1f; i < 1f; i += 0.1f)
System.out.println(i);
I get
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.
解决方案
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 %.1f,如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?的全部内容,更多相关java内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复