5

I trying to make recursive function but I get this error: not all code paths return a value I know why I get this error its because the if not returning something but I don't want it to return something... How to bypass this error? (It should really be just warning)

    private double calculate(double money, int months)
    {
        months--;
        if (months != 0)
            calculate(profit * 0.3, months);
        else
            return profit;
    }

Edit: I call it like that when user click the button

    private void bCalculate_Click(object sender, EventArgs e)
    {
        profit = double.Parse(tbMoney.Text);
        months = int.Parse(tbMonth.Text);
        tbPpofit.Text = calculate(profit,months+1).ToString();
    }

If I write return like you say it will not give the result that i need

5
  • I don't want it to return something but your function must return a double, Commented Dec 15, 2012 at 16:17
  • You probably want return calculate(profit * 1.3, months); but we have to guess. And of course recursion isn't the best approach here. Commented Dec 15, 2012 at 16:28
  • 2
    You do not recursion to do this calculation. Commented Dec 15, 2012 at 16:29
  • Ok than you guys.. I will do something else. Commented Dec 15, 2012 at 16:30
  • I agree with Maarten. There is a non-recursive solution to this problem. Commented Dec 15, 2012 at 17:45

2 Answers 2

11

Simply add a return to the recursive branch:

  if (months != 0)
        return calculate(profit * 0.3, months);
  ...
Sign up to request clarification or add additional context in comments.

Comments

5

Add a return value to your code for recursion:

  if (months != 0)
        return calculate(profit * 0.3, months);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.