1

如果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;
    }
}
4

1 回答 1

8

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

于 2012-08-01T21:04:32.623 回答