[英]When I use "n--" instead of "n-1" why do I get stackoverflow error?
在这段代码中,它是一个递归打印元素 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+" ");
}
}
输出:
Exception in thread "main" java.lang.StackOverflowError
//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+" ");
}
}
输出:
1 2 3 4 5
n--
返回n
的值,然后递减n
。 所以在你的情况下,它变成了一个无限循环,因为n
永远不会改变。 您可以使用--n
而不是先递减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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.