简体   繁体   中英

c# recursive function not all code paths return a value

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

Simply add a return to the recursive branch:

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

Add a return value to your code for recursion:

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

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