“Recursive on All Control Paths” error when implementing factorial function

我的未来我决定 提交于 2019-12-04 10:25:16

There are two critical elements to a recursive function definition:

  • a recursive call to itself
  • a termination condition

You appear to be missing the termination condition. How would factorial() quit calling itself forever?

You defined a recursive function (i.e. basically a function that calls itself), but you have not defined an exit condition. You are calling factorial again right before the return, so the function will never end, calling itself over and over again.

You need to add a branch in there, i.e.

if (set_number == 0)
{
   return 1;
}
else
   return set_number * factorial(set_number - 1);

You are missing a base case. Factorial should return 1 for set_number <= 1

This function will result in infinitive recursion because it never stops calling itself:

int factorial(int set_number)
{
    int cal;
    cal = set_number * factorial(set_number - 1);
    return cal; 
}

This is what you want:

int factorial(int n)
 {
  if (n<=1)
    return(1);
  else
    n=n*factorial(n-1);
    return(n);
 }
int factorial(int set_number)
{   
   return set_number == 1?1:set_number * factorial(set_number - 1);
}

Your factorial function doesn't terminate on one, it just recurses indefinitely.

int factorial(int set_number)
{
    if (set_number <= 1)
        return 1;
    return set_number * factorial(set_number - 1);
}

Your coding style is also pretty poor, it looks very C-like. There's no need for factorial and combination to be defined after main, and you declare all your vars at the top, no declarations and initializations mixed?

Also, your main function doesn't actually do what the specification says it should - you never initialized or assigned to the combinations variable nor called the combination function, your variables are terribly named, etc. But this is your homework, not mine.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!