我在從1^2到n^2遞歸添加Java中的整數時遇到了一些麻煩。 我希望能夠遞歸地在recurvMath方法中做到這一點,但我所得到的是一個無限循環。遞歸添加從1^2到n^2的整數
import java.util.Scanner;
public class Lab9Math {
int count = 0;
static double squareSum = 0;
public static void main(String[] args){
int n = 0;
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the value you want n to be: ");
n = scan.nextInt();
Lab9Math est = new Lab9Math();
squareSum = est.recurvMath(n);
System.out.println("Sum is: "+squareSum);
}
public int recurvMath(int n){
System.out.println("N:" +n);
if(n == 0){
return 0;
}//end if
if (n == 1){
return 1;
}//end if
if (n > 1){
return (recurvMath((int) ((int) n+Math.pow(n, 2))));
}//end if
return 0;
}//end method
}//end class
我不完全掌握遞歸定義這個性質,因爲我知道,我能到這裏:
return (int) (Math.pow(n, 2));
,但我不能正確地納入recurvMath方法的調用爲了它的工作。 任何幫助,將不勝感激。謝謝!
爲了達到這個目的,或許你應該把兩件或兩件以上的東西放在一起? – hobbs 2014-11-25 05:42:53
你爲什麼要遞歸地做這件事? 'int s = 0; for(int i = 1; i
2014-11-25 05:44:03
@ElliottFrisch我想了解java中的遞歸。有什麼更好的方法來嘗試編程! – ekep23 2014-11-25 05:50:01