这是我用来递归计算数字b的阶乘结束处的零数的函数。 然而,由于使用的代码我得到运行时错误。请原谅我的天真,但在此任何帮助将不胜感激。
int noz(int b)
{
int c=0;
int e = b;
if(e < 5)
return 0;
while(e > 0)
c = c + (e/5) + noz(e/5);
return c;
}
答案 0 :(得分:4)
您遇到“运行时错误”,因为:
int c;
...
while(e > 0)
c = c + (e/5) + noz(e/5); // <-- HERE
您正在使用未初始化的本地变量c
,它会产生 未定义的行为 。
您可以对此变量进行零初始化以防止它发生:
int c = 0;
并且还要注意,如果函数的参数大于或等于5
,则此函数不会返回任何内容(感谢@Paul R指出这一点),另一个问题是你有条件e > 0
的循环,但循环不会改变e
的值,使其无限循环。
你的功能可能看起来像这样(我不确定这里所需的逻辑究竟是什么):
int noz(int b)
{
int c = 0;
if (b < 5)
return 0;
else
return c + (b/5) + noz(b/5);
}
答案 1 :(得分:0)
//count n! tail zero
int noz(int n){
int count;
if(n < 5) return 0;
count = n / 5;
return count + noz(count);
}