为什么这段代码会在结果中加1?

时间:2012-08-01 20:56:10

标签: java recursion

如果if (n > 0)它返回正常结果,但是if (n >= 0)它返回正常结果+ 1,我不明白,因为0 * 0 = 0.如果有人知道为什么这样做我我很想明白这一点。

import java.util.*;

// Recursive method returns sum of first n squares
public class RecursiveSum
{
    public static void main(String[] args)
    {
        while (true)
        {
            Scanner keyboard = new Scanner(System.in);

            System.out.println("Enter a number:\tIf you want to exit, enter a negative number.");

            int n = keyboard.nextInt();

            if (n < 0)
                System.exit(0);

            System.out.println("sum(" + n + ") = " + sum(n));
        }
    }

    public static int sum(int n)
    {
        int sum2 = n * n;

        if (n >= 0)
            sum2 += sum(n - 1);

        return sum2;
    }
}

1 个答案:

答案 0 :(得分:8)

if(n>=0)使该方法以-1作为参数递归调用。并sum(-1) == -1 * -1 == 1