作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想实现这个程序,但它在每次函数调用时都会抛出错误并运行无限循环。
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/
我是一名优秀的程序员,十分优秀!