質問を解決している間(コメントにはコード内にあります)if文(結果を表示)は機能しません。エラーを理解するのを手伝ってください。それはコンパイルされて実行されますが、出力は表示されません。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;
}
}
}
}
ありがとうございますが、(4/n)を加算または減算する際に、piの値が増減するので機能しません。例えば、最初の10カウントは、4.000000,2.6666667,3.466667,2.895238,3.39683,2.976046,3.283738,3.017072,3.252366,3.041840となる。それは昇順または降順で連続的ではない。 – kailasneupane
'if(Math.abs(pi-PI)<0.000005)'を試してください – saka1029