所以我有一个简单的 for 循环:
double bg = 5.0;
double f = 0.0;
for(double i = 0; i <= bg; i += 1)
{
f = f + ((2 * i + 1)*0.1);
if(i == bg)
{
System.out.printf ("%.1f" , f);
}
}
当我每次迭代将 i 增加 1 时,它工作得很好。 但是当我执行 i += 0.1 时,它不会打印 f 。 有什么想法吗?
最佳答案
你不能这样比较 float 。
通常使用类似的方法检查两个 float ( double )的相等性
if (Math.abs(i - bg) < 0.00001f)//0.00001f 是非常小的值 - 几乎为零,请选择这个值以满足您的需求
更多信息请查看http://www.cygnus-software.com/papers/comparingfloats/comparingfloats.htm
您的代码应该如下所示
double bg = 5.0;
double f = 0.0;
for(double i = 0; i <= bg; i += 1)
{
f = f + ((2 * i + 1)*0.1);
if (Math.abs(i - bg) < 0.00001f)
{
System.out.printf ("%.1f" , f);
}
}
关于java - 在 for 循环的最后一次迭代上打印,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12663406/