-1
public int sum (int num1, int num2){
    int sum = 0;
        if(num2>num1){
        for (int i = num1; i<=num2; i++){
            sum = sum + i;
            }
        }
        else{
        for (int i = num2; i <= num1; i++){
            sum = sum + i;
            }
        }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum(num1, num2);
    }
}

无限循环问题。任何修复?试图找到两个输入之间所有数字的总和。这是类定义有什么想法吗?

4

4 回答 4

2

代替退货sum(num1, num2);你应该return sum;

于 2013-10-31T04:36:35.243 回答
2

sum()再次调用,并且没有任何条件检查何时中断递归。因此是一个无限循环

正如其他答案所指出的,您必须替换return sum(num1,num2);return sum;

于 2013-10-31T04:32:55.460 回答
0
public int sum (int num1, int num2)
{
   int sum = 0;
   if(num2>num1)
   {
        for (int i = num1; i<=num2; i++)
        {
            sum = sum + i;
         }
   }
   else
   {
        for (int i = num2; i <= num1; i++)
        {
            sum = sum + i;
        }
    }
    System.out.println("The sum between " +num1+ " and " +num2+ " equals " + sum);
    return sum;  
  }

你在做递归调用这就是问题..

于 2013-10-31T04:33:54.383 回答
0

您正在通过递归调用该函数return sum(num1, num2);。所以 return sum(num1, num2);改为return sum;

于 2013-10-31T04:34:30.820 回答