2014-10-09 31 views
0

我的任務是使用他在課堂給我們的算法計算Pi,確定正確的數字,並使用while循環和遞歸方法估計Pi爲六位數。但是我的「超級智能教授」並沒有告訴我們關於遞歸方法的流血事件,當我給他發電子郵件時,他因爲沒有通過查看而感到憤怒。這是我的代碼到目前爲止,我遺漏了我的while循環方法和遞歸方法,因爲我不知道如何去做。使用while循環和遞歸方法計算Pi(Java)

public static final double REAL_PI = 3.14159;//PI is the value prof gave us on the handout 
public static double Pi = 0; //Pi is the value of Pi that this program calculates 
public static int m = 0; 

public static void main (String [] args) 
{ 
    Algorithm(); //calls on method of calculating pi 
    System.out.println("Calculated pi: " + Pi); //prints out pi 
    countDigits(Pi); //calls on countdigits method 
    System.out.println("Number of digits: " + c); //has the computer print out the count because that's how many digits are the same 
    PiRecur(); //calls on estimate digits method 
} 

public static double Algorithm() //should return a double (pi) 
{ 
    for(m=1; m<=100000; m++) 
    { 
     Pi += 4*(Math.pow(-1, m-1)/((2*m)-1));//Math.pow uses math package to calculate a power to use the algorithm 
    } 
    return Pi; 
} 

public static int countDigits (double Pi) 
{ 
    int a = (int) Pi; //the int cast makes Pi and REAL_PI into integers so the program can compare each digit separately 
    int b = (int) REAL_PI; 
    int c = 0; 
    int count = 0; 
    while(a == b)//if m less then or equal to 100,000 then while loop runs 
    { 
     count ++; 
     a = (int) (Pi*(Math.pow(10,count))); //if a=b then the computer will multiply Pi and REAL_PI by 10 
     b = (int) (REAL_PI*(Math.pow(10,count))); 
     /*when you input a and b 
     * while loop compares them 
     * if a = b then loop continues until a doesn't equal b and loop ends 
     */ 
    } 
    c = count; //gives c the value of the count so it can be used outside the method 
    return count; 
} 

}

+2

那麼,什麼是你的問題? – Leistungsabfall 2014-10-09 18:15:47

+0

如何使用while循環和使用不同算法的遞歸方法來估計pi到6位數? – KazuoKatiushi 2014-10-09 18:24:35

+1

請遵守Java的命名約定。這段代碼難以理解 - 方法應該在'camelCase'中。 Pascal案例是爲類保留的。 – 2014-10-09 18:32:30

回答

2

我不知道如何使用while循環和遞歸循環會喜歡,因爲我看不懂你的教授的心意,但我能想到的兩種不同的解決方案,一個解決方案,使用一個或另一個。

使用while循環:

你不(在你的榜樣100000)運行算法的重複任意數量的,希望你有足夠接近預期的結果。你使用一個while循環,並且在每次迭代中檢查當前Pi的計算是否足夠接近目標。

public static double Algorithm() 
{ 
    int m = 1; 
    double Pi = 0.0; 
    while (countDigits(Pi) < 6) { 
     Pi += 4*(Math.pow(-1, m-1)/((2*m)-1)); // I'm assuming this formula works 
     m++; 
    } 
    return Pi; 
} 

使用遞歸:

同樣的解決方案可以被翻譯成一個遞歸。這次,您提供初始索引m(1)和初始值Pi(0)至Algorithm。該方法將m'th term添加到Pi。如果Pi的新值不夠好(由countDigits確定),則進行遞歸調用,將第0123項添加m+1Pi,並再次檢查新值是否足夠好。當Pi的值爲6位數字時,遞歸會停止。

public static double Algorithm(int m,double Pi) 
{ 
    Pi += 4*(Math.pow(-1, m-1)/((2*m)-1)); 
    if (countDigits(Pi) < 6) 
     Pi += Algorithm(m+1,Pi); 

    return Pi; 
} 

與您通話的方法:

Algorithm (1,0.0); 
+0

好!謝謝,我會試着看看它是否會起作用! – KazuoKatiushi 2014-10-09 19:31:24

+0

獲得了while循環的工作! – KazuoKatiushi 2014-10-09 19:35:54

+0

遞歸方法不斷給我一個堆棧溢出錯誤的if語句 – KazuoKatiushi 2014-10-09 19:40:00