這是我與本網站的第一次互動,我聽到了很好的東西,希望我能找到我正在尋找的答案。我正在學習Java並在我的高中使用計算機科學課程中的Eclipse IDE,並且遇到了一個問題,我的老師和我都無法解決。這裏是說明。數學線只在循環中運行一次
「德國數學家GottfriedLeibniz開發的後續方法來近似π值
π/ 4 = 1 - 1/3 1/5 + - + 1/7 ...
編寫一個程序,允許用戶指定該近似值中使用的迭代次數並顯示結果值。「
現在的代碼。
import java.util.Scanner;
public class GottfriedLeibnizPi {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.print("Enter how many iterations you want to go to: ");
int iterations = reader.nextInt();
double pi = 0;
if (iterations >= 0) {
for (int count = 0; count <= iterations - 1; count++) {
System.out.println("pi: " + pi + " count: " + count); //debug statement to show pi and count before running the code
if (count % 2 == 0) {
pi = pi + (1/(1 + (2 * count))); // first to run. starts at pi + 1 and every other loop adds 1/(1+2n)
} else {
pi = pi - (1/(1 + (2 * count))); // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n)
}
System.out.println("pi: " + pi + " count: " + count + "\n"); //debug statement to show pi and count after running the code
}
pi = pi * 4; //obtains the true value of pi
System.out.println("The value of pi after " + iterations + " iterations is " + pi);
} else {
System.out.println("Please enter a non-negative number");
}
}
}
如果我在提示時輸入5,那麼這裏是帶有調試語句的輸出。
Enter how many iterations you want to go to: 5 pi: 0.0 count: 0 pi: 1.0 count: 0 pi: 1.0 count: 1 pi: 1.0 count: 1 pi: 1.0 count: 2 pi: 1.0 count: 2 pi: 1.0 count: 3 pi: 1.0 count: 3 pi: 1.0 count: 4 pi: 1.0 count: 4
PI值後的5次迭代4.0
我的數學說,答案應該是3.3396 ...但在我的循環數學不出現運行不止一次。我在這裏沒有發現任何接近我的問題的東西,有人知道什麼是錯的嗎?
按我記錄我所做的唯一的錯誤是一個簡單的,愚蠢的一個。謝謝。 – 2012-01-12 21:24:36