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