我正在尝试编写代码,返回给定的整数是否可以被1到20均分,
但我一直收到以下错误:
错误CS0161:'ProblemFive.isTwenty(int)':并非所有代码路径都返回一个值
这是我的代码:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
Run Code Online (Sandbox Code Playgroud)
小智 78
你错过了一个return声明.
当编译器查看您的代码时,它会看到else可能发生但不返回值的第三条路径(您没有编写代码).因此not all code paths return a value.
对于我建议的修复,我return在你的循环结束后放了一个.另一个显而易见的地方 - 添加一个else具有return值的if-else-if- 将打破for循环.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
Run Code Online (Sandbox Code Playgroud)
编译器没有获得在循环的最后一次迭代中返回的复杂逻辑,因此它认为您可以退出循环并最终不返回任何内容.
而不是在最后一次迭代中返回,只是在循环后返回true:
public static bool isTwenty(int num) {
for(int j = 1; j <= 20; j++) {
if(num % j != 0) {
return false;
}
}
return true;
}
Run Code Online (Sandbox Code Playgroud)
注意,原始代码中存在逻辑错误.您正在检查是否num == 20在最后一个条件,但您应该检查是否j == 20.还要检查是否num % j == 0超级丰富,因为当你到达那里时总是如此.
我喜欢打死马,但我只想补充一点:
首先,问题在于并非您的控制结构的所有条件都已得到解决。本质上,你是说如果 a,那么这个,否则如果 b,那么这个。结尾。但如果两者都没有呢?没有办法退出(即不是每个“路径”都返回一个值)。
我的补充一点是,这是一个例子,说明如果可能的话,您应该瞄准单一退出。在本例中,您将执行以下操作:
bool result = false;
if(conditionA)
{
DoThings();
result = true;
}
else if(conditionB)
{
result = false;
}
else if(conditionC)
{
DoThings();
result = true;
}
return result;
Run Code Online (Sandbox Code Playgroud)
因此,在这里,您将始终有一个 return 语句,并且该方法始终在一个地方退出。不过有几件事需要考虑……您需要确保您的退出值在每条路径上都是有效的,或者至少是可以接受的。例如,这个决策结构只考虑了三种可能性,但单个退出也可以作为你最后的 else 语句。或者是吗?您需要确保最终返回值在所有路径上都有效。与拥有 5000 万个退出点相比,这是一种更好的方法。
小智 6
我也遇到了这个问题,并找到了简单的解决方案
public string ReturnValues()
{
string _var = ""; // Setting an innitial value
if (.....) // Looking at conditions
{
_var = "true"; // Re-assign the value of _var
}
return _var; // Return the value of var
}
Run Code Online (Sandbox Code Playgroud)
这也适用于其他返回类型,并提供最少量的问题
我选择的初始值是一个回退值,我能够根据需要重新分配值.