在带有 while 循环的 c 中使用递归的阶乘程序。在此程序中,一旦执行到函数返回语句,它将不会返回到函数调用。相反,它重复执行该功能。谁能告诉我这个程序有什么问题。
#include<stdio.h>
int fact(int n)
{
int x=1;
while(n>1)
{
x=n*fact(n-1);
}
return(x);
}
void main()
{
int n,fact1;
scanf("%d",&n);
fact1=fact(n);
printf("%d",fact1);
}
最佳答案
你的程序进入无限循环的原因是循环
while (n > 1)
x = n * fact(n-1);
从不递减 n
。由于 n
永远不会减少,程序永远不会离开循环。 Peter 在评论中是正确的:将 while
更改为 if
,您将拥有一个正确处理所有正参数的阶乘函数。但是,即使将 while
更改为 if
,您的 fact
也不会有 fact(0) == 1
,这是正确的阶乘函数所必需的。
关于c - 在带有 while 循环的 C 中使用递归函数的阶乘程序 c,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9243312/