Mei*_*Mei 2 c recursion factorial
使用while循环在c中使用递归的因子程序.在该程序中,一旦执行到达函数return语句,它就不会返回到函数调用.相反,它重复执行该功能.任何人都可以告诉我这个程序有什么问题.
#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);
}
Run Code Online (Sandbox Code Playgroud)
程序进入无限循环的原因是循环
while (n > 1)
x = n * fact(n-1);
Run Code Online (Sandbox Code Playgroud)
永不减量n.由于n永不减少,程序永远不会离开循环.Peter在评论中是正确的:将a 更改while为a if,您将拥有一个正确处理所有正参数的阶乘函数.但是,即使更改while为if,您fact也不会拥有fact(0) == 1正确的阶乘函数所需的属性.