简体   繁体   中英

Understanding an error in a recursive function?

I am trying to write a recursive function, but get an error in the line : n + sum(n-1); My compiler is German, so a poor translation of the error message would be: "void value not ignored as supposed to". Thanks for help!

void sum (int n)
{
    if(n==0)
    {
        cout << n << endl;
    }
    else if(n>0)
    {
        n + sum(n-1);
        cout << n << endl;
    }
}

int main()
{
   sum(3);
   return 0;
}

Notice that you've defined the function as

void sum (int n);

This function has no return value. However, in this code:

n + sum(n-1);

You are trying to add n to the return value of sum(n - 1) , which isn't legal because sum(n - 1) doesn't produce a value.

To fix this, you probably will want to change the function so that it returns an int . If you do this, you'll need to make other changes, such as adding return statements into the function, but it should help get you on the right track.

Hope this helps!

sum方法返回void,将其更改为int

int sum (int n)

Your sum() method should return a value, it should return the sum. You should define it like this

int sum (int n)
{
if(n==0)
{
 cout << n << endl;
 return 0;
}
else if(n>0)
{
    cout << n << endl;
    return n + sum(n-1);
 }
 }

You try to add n and sum(n-1), but sum has no return value, so this is an error. You should modify sum to return an int, and add the return statements in the two if bodies.

When you wrote "void sum" you told the compiler that sum would not return anything. This is wrong. Try replacing "void" with int.

I got it. Was kinda stupid from me. It has to be of course n = n + sum(n-1); And an int function. Thanks guys.

  • A recursive function needs to return something in each tail position.
  • A recursive function needs to have made the problem smaller at each recursion.

Here is one example of how to do it:

int sum (int n)
{
    return n == 1 ? 1 : n + sum_rec(n-1);
}

int main()
{
   cout << sum(3) << endl;
   return 0;
}

A better one if you C compiler does tail call optimization:

// just a helper for sum_it
int sum_aux (int n, int accumulator)
{
    return n == 0 ? accumulator : sum_rec(n-1, accumulator + n);
}

int sum_it (int n)
{
    sum_aux(n, 0);
}

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