我的任務是使用他在課堂給我們的算法計算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;
}
}
那麼,什麼是你的問題? – Leistungsabfall 2014-10-09 18:15:47
如何使用while循環和使用不同算法的遞歸方法來估計pi到6位數? – KazuoKatiushi 2014-10-09 18:24:35
請遵守Java的命名約定。這段代碼難以理解 - 方法應該在'camelCase'中。 Pascal案例是爲類保留的。 – 2014-10-09 18:32:30