【问题标题】:c# recursive function not all code paths return a valuec#递归函数并非所有代码路径都返回一个值
【发布时间】:2012-12-03 08:27:22
【问题描述】:

我尝试创建递归函数,但出现此错误:并非所有代码路径都返回值 我知道为什么会出现此错误,因为 if 没有返回某些内容,但我没有希望它返回一些东西......如何绕过这个错误? (应该只是警告)

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

编辑:当用户单击按钮时,我这样称呼它

    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();
    }

如果我像你说的那样写return,它不会给出我需要的结果

【问题讨论】:

  • I don't want it to return something 但你的函数必须返回一个双精度,
  • 您可能想要return calculate(profit * 1.3, months);,但我们必须猜测。当然,递归并不是最好的方法。
  • 你不用递归来做这个计算。
  • 好吧,比你们……我会做点别的。
  • 我同意 Maarten 的观点。这个问题有一个非递归的解决方案。

标签: c# function recursion


【解决方案1】:

只需在递归分支中添加一个返回:

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

【讨论】:

    【解决方案2】:

    将return 值添加到您的代码中以进行递归:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多