java中start与loop_java for-loop问题
我正在制作一個(gè)Java程序來計(jì)算Simpson的積分規(guī)則.這是我的代碼.注意count == 4,9,10,11的輸出值中的第二列數(shù)字.它們不是我需要的數(shù)字,它們不遵循這種模式.我需要這些數(shù)字是準(zhǔn)確的.發(fā)生了什么,我該如何解決?
public static void main(String[] args)
{
double totalS = 0.0;
int count = 0;
for(double i=0; i< 4; i += 0.4 )
{
count++;
totalS += Sfunction(i, count);
System.out.println(count + " " + i + " " + totalS);
}
}
public static double Sfunction(double f1, int count)
{
double value;
if (f1 == 0.0 || f1 == 4.0)
value = Math.cos(Math.sqrt(f1));
else if ((count % 2) == 1)
value = 2 * Math.cos(Math.sqrt(f1));
else
value = 4 * Math.cos(Math.sqrt(f1));
return value;
}
我得到的輸出:
1 0.0 1.0
2 0.4 4.226313639540303
3 0.8 5.478244888601832
4 1.2000000000000002 7.30884788480188
5 1.6 7.911122809972827
6 2.0 8.534897589034324
7 2.4 8.578100205110182
8 2.8 8.168723348285942
9 3.1999999999999997 7.736055200662704
10 3.5999999999999996 6.452869366954546
11 3.9999999999999996 5.620575693860261
解決方法:
每次繞過循環(huán),你都會(huì)在0.4到i的不精確加法中混合錯(cuò)誤.
相反,使用循環(huán)計(jì)數(shù)器的整數(shù)值,并對(duì)其進(jìn)行縮放以獲得更好的近似值:
for ( int count = 0; count < 10; ++count ) {
final double i = 0.4 * count;
System.out.println ( ( count + 1 ) + " " + i );
}
這不會(huì)消除浮點(diǎn)錯(cuò)誤,但這意味著它不會(huì)在每次迭代時(shí)增加.要從輸出中刪除錯(cuò)誤,請(qǐng)將輸出格式化為合理的小數(shù)位數(shù):
for ( int count = 0; count < 10; ++count ) {
final double i = 0.4 * count;
System.out.printf ( "%2d %.1f\n", ( count + 1 ), i );
}
標(biāo)簽:java,for-loop
來源: https://codeday.me/bug/20190711/1437549.html
總結(jié)
以上是生活随笔為你收集整理的java中start与loop_java for-loop问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 省份城市区县三级联动html代码,基于J
- 下一篇: maven工程打包老是报错_maven工