开发者

i want to find the factorial of a given number using recursive function in c.what's wrong with the following program?

#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. Wha开发者_开发百科t 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 don't want the static in your tot declaration.


You misprinted in if statement, it should be

if(x > 1) {
   tot=x*fact(x-1);
}

EDIT: Also tot must be non-static.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜