C语言递归
//递归求n的阶乘#include<stdio.h>
int factorial(int x);
int main()
{
int a,result;
printf("输入一个数(求阶乘):\n");
scanf("%d",&a);
result=factorial(a);
printf("a!=%d",result);
return 0;
}
int factorial(int x)
{
int fac=0;
if(x<0)
printf("%d the data is error!",x);
else if(x==0||x==1)
fac=1;
else
fac=x*factorial(x-1);
return fac;
}
这一串代码是不是有个小问题啊,我如果输入一个负数,还是会输出“a!=0”,有没有什么可以改进的办法呀?谢谢大佬们 本帖最后由 昨非 于 2021-1-7 15:50 编辑
求阶乘只对非负整数
负数时没有阶乘的,加个非法输入的判断就好了
//递归求n的阶乘
#include<stdio.h>
int factorial(int x);
int main()
{
int a, result;
printf("输入一个非负整数(求阶乘):\n");
scanf("%d", &a);
while (a < 0)
{
printf("输入非法,请重新输入:\n");
scanf("%d", &a);
}
result = factorial(a);
printf("a!=%d", result);
return 0;
}
int factorial(int x)
{
int fac = 0;
if (x < 0)
printf("%d the data is error!", x);
else if (x == 0 || x == 1)
fac = 1;
else
fac = x * factorial(x - 1);
return fac;
}
测试结果:
输入一个非负整数(求阶乘):
-5
输入非法,请重新输入:
-3
输入非法,请重新输入:
5
a!=120 本帖最后由 WindyJane 于 2021-1-7 18:33 编辑
int factorial(int x)
{
int fac=0;
if(x<0)
{
printf("%d the data is error!",x);
system("pause");//显示一下 %d the data is error!
exit -1;//异常中断,退出, 不去执行return fac以及后面的显示
}
else if(x==0||x==1)
fac=1;
else
fac=x*factorial(x-1);
return fac;
} WindyJane 发表于 2021-1-7 18:30
int factorial(int x)
{
int fac=0;
谢谢你嗷{:5_92:}
页:
[1]