[英]error in loop with if statement, but gets compiled and terminates without error without displaying expected result
解決問題時(在代碼中作為注釋。)if語句(顯示結果)不起作用。 請幫助我找出錯誤。 它被編譯並運行,但未顯示輸出。
/*
* (Calculating the Value of π ) Calculate the value of π from the infinite series
4 4 4 4 4
π = 4 – --- + --- – --- + --- – ------ + ...
3 5 7 9 11
Print a table that shows the value of π approximated by computing the first 200,000 terms of this
series. How many terms do you have to use before you first get a value that begins with 3.14159?
*/
public class ValueOfPi
{
public static void main(String[] args)
{
int i,count=0;
double pi=0.0,n=1.0,PI=3.14159;
for(i=0;i<200000;i++)
{
count++;
if(count%2!=0)
{
pi=pi+(4/n);
}
else if(count%2==0)
{
pi=pi-(4/n);
}
n=n+2;
if(pi==PI)
{
System.out.printf("terms=%d PI=%f\n",count,pi);
break;
}
}
}
}
if語句不起作用的原因是,您正在比較浮點數是否相等。 每位計算機科學家應該了解的有關浮點運算的頁面說明了原因。
在重新閱讀了OP的問題之后,對於這種情況,我首先將pi的計算值轉換為長度為8個或更多字符的字符串,然后將前7個字符與“ 3.14159”進行比較。
第一個浮點數是不精確的-大約為2的(負)冪的和-(也有3.14159),並且計算出的pi
可以高於或低於給定值。
也將%n
用作\\n
是Linux行末,而不是Windows \\r\\n
。 這可能會阻止刷新行緩沖區以輸出。 (不確定,我有Linux)。
if (Math.abs(pi - PI) < 1.0E-5)
{
System.out.printf("terms=%d PI=%f%n",count,pi);
break;
}
另外,您可以使用Math.PI
以獲得更好的近似值。 現在,您需要冒比需要0.00001不精確度的PI
更精確的pi
風險。
使用==或太小的eps余量,例如0.00000001可能會導致幾乎無限循環。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.