递归 - 递增数字并返回

时间:2014-05-15 21:00:36

标签: java recursion

好的,这一定是非常愚蠢的......我的陈述是返回2:

  • 当我打印出值都正确
  • 以某种方式返回陈述错误

代码:

public static void main (String [] args)
{
    System.out.println(countToTen(1));
}

public static int countToTen(int last_answer){
    last_answer++;
    if(last_answer != 10){
        countToTen(last_answer);
    }
    return  last_answer;
}

6 个答案:

答案 0 :(得分:4)

尝试将if语句替换为:

if(last_answer != 10){
    return countToTen(last_answer);
}

如果没有return语句,则会执行递归调用,但永远不会返回计算结果。

破坏代码的调用顺序如下:

countToTen(1)
 -> countToTen(2)
 -->  countToTen(3)
 ---> more calls to countToTen()
 --- ... --> countToTen(10) // do nothing, and return to the top-level method call
 -> return 2 // 2 because you incremented it using lastAnswer++

答案 1 :(得分:2)

您的函数返回第一次调用的值。它是由++语句递增一次的初始值(1),因此函数返回2.

整数在Java中通过值传递,递增函数内部传递的值不会改变外部的值:

int x = 0;
v(x);
// x still 0 here.

void v(int x) {
  x = 100;
}

答案 2 :(得分:0)

public static void main (String [] args)
{
    System.out.println(countToTen(1));    
}

public static int countToTen(int last_answer)
{    
    last_answer++;

    if(last_answer != 10)
    {
        return countToTen(last_answer); //Here was the error
    }

    return  last_answer;
} 

答案 3 :(得分:0)

试试这个:

public static int countToTen(int last_answer){

  last_answer++;

  if(last_answer != 10){
    return countToTen(last_answer);
  }
  else {
    return last_answer;
  }
} 

答案 4 :(得分:0)

如果你想要打印出1,2,3,4 ... 10,你需要分别在每个阶段打印答案

public static void main (String [] args){
    countToTen(1);
}

public static void countToTen(int last_answer){

    System.out.println(last_answer);
    last_answer++;

    if(last_answer <= 10){
    countToTen(last_answer);
    }
} 

答案 5 :(得分:0)

我的建议

public static int countToTen(int last_answer){

   last_answer++;

    if(last_answer < 10){
        return countToTen(last_answer);
    } else {
        return last_answer;
    }
}

您没有通过引用传递参数,它是一个副本。您正在方法的上下文中对last_answer进行修改,但此更改不会传播到外部,因为最后您返回last_answer ++