2015-02-09 43 views
0

如果有人能向我解释我写的这段代码如何不接近我认为会产生的结果,我真的会非常喜欢。我写的代码试图证明int n将是n = 4所以在我的头,在纸上,我想我在一步一步的结果会是如下:试图找出递归基础知识

  1. 4 * 4 +(3)= 19
  2. 3×3 +(2)= 11
  3. 2 * 2 +(1)= 5
  4. 1 * 1 +(0)= 1
  5. 返回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; 
        } 
    
+4

您可以使用调试器自行穿过它。 – 2015-02-09 22:43:30

+0

这是如何工作的? – 2015-02-09 22:44:22

+1

您的IDE应该有一个“调试”模式,它可以让您逐行单步执行代码。 – 2015-02-09 22:44:48

回答

1

下面是递归的步骤,首先n4

intValue(4) 
    n is not 0. total is 4 * 4 + intValue(3) 
    intValue(3) 
    n is not 0. total is 3 * 3 + intValue(2) 
    intValue(2) 
     n is not 0. total is 2 * 2 + intValue(1) 
     intValue(1) 
     n is not 0. total is 1 * 1 + intValue(0) 
     intValue(0) 
      n is 0, intValue(0) returns 0. 
     1 * 1 + 0 = 1. 
     Print Recursive value: 1, intValue(1) returns 1. 
     2 * 2 + 1 = 5. 
     Print Recursive value: 5, intValue(2) returns 5. 
    3 * 3 + 5 = 14. 
    Print Recursive value: 14, intValue(3) returns 14. 
    4 * 4 + 14 = 30. 
    Print Recursive value: 30, intValue(4) returns 30. 

回到主,初始调用返回30,并且它打印recursive value 30

递归调用不返回n - 1本身被添加;它将返回intValue再次以n - 1作为参数的结果。

0

所以你的递推公式是

total = n * n + intValue(n-1); 

而当你有4个运行它,它是

4 * 4 + intValue(3) 

在这种情况下的intValue(3)

3 * 3 + intValue(2) 

在这种情况下intValue(2) i小号

2 * 2 + intValue(1) 

在这种情况下的intValue(1)

1 * 1 + intValue(0) 

在这种情况下的intValue(0)

0 

在这种情况下回去,的intValue (1)

1 * 1 + intValue(0) = 1*1 + 0 = 1; 

在这种情况下回去,的intValue(2)

2 * 2 + intValue(1) = 2 * 2 + 1 = 5 

在这种情况下的intValue(3)

3 * 3 + intValue(2) = 3 * 3 + 5 = 14 

在这种情况下的intValue(4)

4 * 4 + intValue(3) = 4 * 4 + 14 = 30 
+0

为什么一旦它一路下降到0不会返回0?为什么它会备份? – 2015-02-09 22:53:43

+0

@JeffGreenwood:假设你有5个函数'intValueA','intValueB','intValueC'等,每个函数都调用下一个函数,而不是它自己。这是否回答你的问题? – 2015-02-09 22:54:47

+0

例如,由于“intValue(2)”的结果为“5”,并且“intValue(3)”的结果取决于“intValue(2)”,例如“5”。我试图编辑我的帖子,使其更清晰。 – EpicPandaForce 2015-02-09 22:55:40

0

关于递归的事情是,它一直调用自己,直到它达到n == 0返回点。你试图在纸上写出来的方式是颠倒的。

它不会评估你的方程,直到n == 0,并且所有的递归调用都基本上堆叠等待结果。所以它得到了这样的结果(括号中的每个op等待递归调用的结果):

total = 4 * 4 +(3 * 3 +(2 * 2 +(1 * 1 + 0)))

为了评价 5.(栈顶)中,n = 0,则返回0
4. n = 1时,1 * 1 + 0,返回1
3. n = 2的,2 * 2 + 1,返回5
2. N = 3,3 * 3 + 5,返回14
1 N = 4,4 * 4 + 14,返回30