如果有人能向我解释我写的这段代码如何不接近我认为会产生的结果,我真的会非常喜欢。我写的代码试图证明int n
将是n = 4
所以在我的头,在纸上,我想我在一步一步的结果会是如下:试图找出递归基础知识
- 4 * 4 +(3)= 19
- 3×3 +(2)= 11
- 2 * 2 +(1)= 5
- 1 * 1 +(0)= 1
返回0
有人能告诉我为什么不是这样?并引导我完成递归步骤?
public static void main(String[] args) { Scanner kbd = new Scanner(System.in); int n; System.out.println("Enter a number: "); n = kbd.nextInt(); System.out.println("recursive value "+intValue(n)); } public static int intValue(int n) { int total; int x; if(n == 0) return 0; else total = n * n + intValue(n-1); System.out.println("Recursive total: "+total); return total; }
您可以使用调试器自行穿过它。 – 2015-02-09 22:43:30
这是如何工作的? – 2015-02-09 22:44:22
您的IDE应该有一个“调试”模式,它可以让您逐行单步执行代码。 – 2015-02-09 22:44:48