2012-01-12 38 views
3

這是我與本網站的第一次互動,我聽到了很好的東西,希望我能找到我正在尋找的答案。我正在學習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 ...但在我的循環數學不出現運行不止一次。我在這裏沒有發現任何接近我的問題的東西,有人知道什麼是錯的嗎?

回答

4

該問題似乎是由整數除法引起的舍入。嘗試用這種替代你的代碼的相關部分:

if(count % 2 == 0){ 
    pi = pi + (1/(1 + (2.0 * count)));  // first to run. starts at pi + 1 and every other loop adds 1/(1+2n) 
} 

else{ 
    pi = pi - (1/(1 + (2.0 * count)));  // first to run. starts at pi - 1/3 and every other loop subtracts 1/(1+2n) 
} 

由於「1」的分子是一個整數,「(1 +(2 *計數))」中的分母也是一個整數,你將得到整數除法,它將截斷除法中的任何餘數。由於分母在這種情況下將大於或等於1,所以1 /(大於1的正整數)總是以整數除法結果爲0。通過向其中一個整數添加小數,Java會將其視爲double而不是執行整數除法。

所以實際上,線的執行沒有問題。當我通過上述更改運行代碼時,我會得到與老師給出的答案相同的答案。

The value of pi after 5 iterations is 3.3396825396825403 
+0

按我記錄我所做的唯一的錯誤是一個簡單的,愚蠢的一個。謝謝。 – 2012-01-12 21:24:36

1

INT/INT給出INT型,由您鬆divison的小數部分(3/2給出1)。所以你需要 -

pi = pi + (1.0/(1.0 + (2 * count))); // Notice the 1.0 

同樣在另一種情況。

1

在兩種情況下:

pi = pi + (1/(1 + (2 * count))); // (1/(1 + (2 * count))) everything here is an int so, so you are losing . and everything after . 

改變它

pi = pi + (1d/(1 + (2 * count)));