概述
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 %.1f,如何在Java中以0.1f的增量在0.1f和1.0f之间进行迭代?所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复