#include<stdio.h>
int fact(int i);
void main()
{
int j;
j=fact(4);
printf("%d",j);
}
int fact(int i){
int x=i;static int tot=1;
if(x<1){
tot=x*fact(x-1);
}
return tot;
}
Please help me with this code. What is wring in this code?
You do not have a base condition in the fact function.
You need to check:
if(i == 1){
return 1;
}else{
return i * fact(i - 1);
}
if(x<1)
Are you sure you didn't mean x > 1
?
Also, I would get rid of static
in your declaration of tot
. This treats tot
similarly to a global variable. You don't need that. Since tot
is always assigned before read it looks like it's not harmful here, but generally speaking it seems like a red flag.
You misprinted in if statement, it should be
if(x > 1) {
tot=x*fact(x-1);
}
EDIT: Also tot
must be non-static.
您不希望在tot
声明中使用static
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.