在此代码中,这是一个递归打印元素 1 到 5 的程序,当我使用n--代替 时n-1,出现堆栈溢出错误。而当n-1使用时,代码运行得很好。不应该n--和n-1在此代码中工作相同吗?
//when using n--
class PrintElements1to5
{
public static void main(String[] args)
{
recursivePrint(5);
}
static void recursivePrint(int n)
{
if(n<1)
return;
recursivePrint(n--);
System.out.print(n+" ");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
Exception in thread "main" java.lang.StackOverflowError
Run Code Online (Sandbox Code Playgroud)
//when using n=n-1
class PrintElements1to5
{
public static void main(String[] args)
{
recursivePrint(5);
}
static void recursivePrint(int n)
{
if(n<1)
return;
recursivePrint(n-1);
System.out.print(n+" ");
}
}
Run Code Online (Sandbox Code Playgroud)
输出:
1 2 3 4 5
Run Code Online (Sandbox Code Playgroud)
小智 5
n--首先返回 的值n,然后递减n。所以在你的情况下,它变成了一个无限循环,因为n它永远不会改变。您可以--n改为先使用 which 递减n,然后返回 的值n。让我们举一个更简单的例子。
int x = 3;
System.out.println(x - 1); // prints 2, x is still 3
System.out.println(x--); // prints 3, x becomes 2
System.out.println(--x); // prints 1, x becomes 1
Run Code Online (Sandbox Code Playgroud)