【发布时间】:2020-11-10 22:59:38
【问题描述】:
如果我输入零或负值,以下代码将正确返回。但是,如果我输入任何正值,它什么都不做。
有人可以解释为什么吗?我的期望是,它应该返回正数的阶乘。
#include<stdio.h>
int functionfact(int);
void main()
{
int x,fact;
printf("Input an integer value:\n");
scanf("%d",&x);
if (x<0)
printf("Please enter positive value!!");
else if (x==0)
printf ("The factorial of 0 is 1");
else
{
fact=functionfact(x);
printf("The factorial of %d is %d",x,fact);
}
}
int functionfact(int n)
{
return(n*functionfact(n-1));
}
【问题讨论】:
-
functionfact什么时候停止? -
functionfact函数没有任何终止条件。 -
提示:例如5 您正在计算 5*4*3*2*1*0*-1*-2*-3*... 等等。您需要在 1 处停止。
-
这能回答你的问题吗? C recursive function to calculate Factorial