我为我的班级编写的程序需要从 0.5 到 42.9 以 0.1 计数的行以及其他几行。由于双精度数不准确,程序从 0.1 计数到 0.7,所以下一个数字变为 0.799999999 而不是 8。我对纠正这个问题的代码有点怀疑。我想说它与 Math.abs 和 EPS 有关,但我不确定。任何意见,将不胜感激。
{
System.out.println(" ");
final double MAX2 = 43;
for (double row = 0.5; row<MAX2; row+=0.1)
{
System.out.print(row);
if(row != MAX2 -1)
{System.out.print(",");
}//SOP COMMA
}//SOP ROW3
}//.5,42.9
最终结果是
0.5,0.6,0.7,0.7999999999999999,0.8999999999999999,0.9999999999999999,1.0999999999999999,1.2,1.3,1.4000000000000001,1.5000000000000002,1.6000000000000003,1.7000000000000004,1.8000000000000005,1.9000000000000006,2.0000000000000004,2.1000000000000005,2.2000000000000006,2.3000000000000007,2.400000000000001,2.500000000000001,2.600000000000001,2.700000000000001,2.800000000000001,2.9000000000000012 etc .