gpt4 book ai didi

c#递归函数并非所有代码路径都返回一个值

转载 作者:太空狗 更新时间:2023-10-29 22:10:56 25 4
gpt4 key购买 nike

我试图创建递归函数,但出现此错误:并非所有代码路径都返回一个值 我知道为什么会出现此错误,因为 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 它不会给出我需要的结果

最佳答案

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

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

关于c#递归函数并非所有代码路径都返回一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13893889/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com