我想通過迭代近似pi。這只是代碼的一部分。我試圖把這個公式放入java中:pi = 4(1 - 1/3 + 1/5 - 1/7 + 1/9 + ... +(( - 1)^(i + 1))/(2i-1))。我的問題是這個方程的總和(在我的代碼中說明)。如果用戶繼續輸入y,程序應該將i乘以2並計算pi直到用戶輸入n,然後返回到主菜單。近似pi通過迭代JAVA
else if(input == 4)
{
System.out.print("i=1 pi=4.0\tWould you like to continue? (y|n) ");
char y = keyboard.next().charAt(0);
if (y =='y')
{
for (int i=2; i<=1000; i=i*2)
{
int sum = 0;
double pi =4 * (Math.pow(-1, i+1)/(2*i-1));
//Right here, how do I modify it to get a sum across a multitude of i's?
System.out.print("i=" + i + " " + "pi" + "=" + pi + "\tcontinue (y|n)? ");
keyboard.next().charAt(0);
}
}
else
{
}
你爲什麼要把'i'乘以2?應該不是'i ++'而是? – Henry 2014-09-25 15:31:30
'Math.pow(-1,i + 1)'這也行不通。 – Henry 2014-09-25 15:32:36
i的增量應該是前一個的兩倍 – awxf218 2014-09-25 15:35:17