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