gpt4 book ai didi

java - 递归程序来加减一个数

转载 作者:行者123 更新时间:2023-12-02 10:10:12 24 4
gpt4 key购买 nike

我想实现这个程序,但它在每次函数调用时都会抛出错误并运行无限循环。

class abc
{
public static void main(String[] args) {
int n=16;
calll(n);
}
static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
n=n+5;
calll(n);
return n;
}

}
}

最佳答案

您的函数没有结束条件。

无论 n 是否大于 5,您都会运行 calll 函数,然后该函数会再次运行 calll 函数直至无穷大。

您需要一个结束递归的条件,例如将调用函数更改为:

static int calll(int n)
{
if(n>0)
{
n=n-5;
calll(n);
return n;
}
else
{
return n;
}

}

但是这个函数仍然毫无意义,因为你实际上并没有对 n 做任何事情。请记住,您在 main 函数中定义的 n 永远不会被修改。

关于java - 递归程序来加减一个数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55058886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com