-1

The last return statement executed in the factorial function is return 1; why does it return the right value and not 1 ?

#include <iostream>
using namespace std;

unsigned int factorial(unsigned int);

int main ()
{
    unsigned int a=4;
    cout<<factorial(a);

    return 0;
 }

 unsigned int factorial(unsigned int a)
  {
      if (a==0)
            return 1;   
      else
        return a*(factorial(a-1));
   }
4

5 回答 5

2

Maybe this helps

factorial(5)
   calls factorial(4)
      calls factorial(3)
         calls factorial(2)
            calls factorial(1)
            returns 1
         returns 2*1 (equals 2)
      returns 3*2 (equals 6)
   returns 4*6 (equals 24)
returns 5*24 (equals 120)

As you can see it's the first return statement that returns 1, not the last.

于 2013-09-23T04:58:29.407 回答
2

The factorial function calls itself until a == 0. factorial does stop calling itself and does return 1 but it does not immediately return to main() because it needs to go back through all the calls to itself first.

A function that calls itself is called a recursive function. See this link:

http://http://www.learncpp.com/cpp-tutorial/710-recursion/

Or this link:

http://www.youtube.com/watch?v=UFL7GkAHnTQ

于 2013-09-23T05:07:51.043 回答
1

The statement return 1; is the stop condition in the recursive call to the factorial function.

Check that link about the recursion concept: http://pages.cs.wisc.edu/~calvin/cs110/RECURSION.html

In simple words: Starting by a call like factorial (3), the sequence of calls will be:

--> return 3 * factorial(2)
--> return 3 * 2 * factorial(1)
--> return 3 * 2 * 1 * factorial(0)
& Finally

--> return 3 * 2 * 1 * 1 which is equal to 6
于 2013-09-23T04:56:58.703 回答
1

why does it return the right value and not 1 ?

Hm... perhaps because of

return a * factorial(a - 1);

?

于 2013-09-23T04:59:14.260 回答
0

Because the call to factorial results in a chain of factorial calls which are multiplied together, the last of which is factorial(0), which returns 1.

So, factorial(4) is computed like this:

factorial (4) = 4 * (factorial(3))
factorial (3) = 3 * (factorial(2))
factorial (2) = 2 * (factorial(1))
factorial (1) = 1 * (factorial(0))
factorial (0) = 1

Putting this together:

factorial (4) = 4 * (3 * (2 * (1 * 1) ) )
于 2013-09-23T04:57:26.823 回答