简体   繁体   中英

C# using recursion with only one return

I have the following recursive function

public int Factorial(int number_to_calculate)
{
    if (StackChanged != null)
    {
        StackChanged(new CustomEventArgs(StackValue, Result));
    }

    System.Threading.Thread.Sleep(wait_time);
    if (number_to_calculate == 0)
    {
        StackValue--;
        return 1;
    }
    else
    {
        StackValue++;
        Result = (number_to_calculate * Factorial(number_to_calculate - 1));
    }

    if (StackChanged != null)
    {
        StackChanged(new CustomEventArgs(StackValue, Result));
    }
    StackValue--;
    System.Threading.Thread.Sleep(wait_time);
    return Result;
}

Apparently my supervisor is not ok with me having 2 returns, but wants the function to be recursive. So I only need one return. I already tried using an accumulator with goto beginning,in order to have only one return, but i need to increment StackValue every time the function calls itself and decrement it when it comes out of recursion. This way I won't know when it comes out.

Does anyone have any ideas?

The simplest way to make a function have a single return statement is to store the value to return in a variable, and then return it at the end. So you would convert something like the following:

int myFunc() {
    if (cond)
        return x;
    else
        return y;
}

Into something like this:

int myFunc() {
    int returnValue;
    if (cond)
        returnValue = x;
    else
        returnValue = y;
    return returnValue;
}

This principle can be applied in general to any method, as long as you take care that when you change a return statement to variable assignment, you have conditions setup so the rest of the code is skipped.

However, a requirement like this is rather arbitrary. It is expected in general with recursion to have multiple return statements.

Instead of

if (number_to_calculate == 0)
    {

        StackValue--;

        return 1;

    }...

do

if (number_to_calculate == 0)
    {

       result = 1;

    }
int Factorial(int number) 
        {
            int result = 1;
            StackValue++;
            if (StackChanged != null)
                StackChanged(new CustomEventArgs(StackValue, Result));

            if (number > 1) 
            {       
                System.Threading.Thread.Sleep(wait_time); 
                result = number * Factorial(number - 1);
            }

            StackValue--;
            if (StackChanged != null)
                StackChanged(new CustomEventArgs(StackValue, Result));

            return result;
        }

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM