c#返回错误“不是所有的代码path返回一个值”

我试图编写的代码,返回给定的整数是否或不能整除1到20,但我不断收到“错误CS0161:'ProblemFive.isTwenty(int)':不是所有的代码path返回一个值“

请帮忙。

这是我的代码:

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语句。

当编译器查看你的代码时,它会看到第三个可能发生但不返回值的path(你没有编码的elsepath)。 因此not all code paths return a value

对于我build议的修复,我在循环结束后放置了一个return 。 另一个显而易见的地方 – 添加一个elseif-else-ifreturn值会打破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 } 

编译器在循环的最后一次迭代中没有得到复杂的逻辑,所以它认为你可以退出循环,最终不会返回任何东西。

而不是在最后一次迭代中返回,只是在循环后返回true:

 public static bool isTwenty(int num) { for(int j = 1; j <= 20; j++) { if(num % j != 0) { return false; } } return true; } 

注意,原始代码中有一个逻辑错误。 你正在检查是否在最后一个条件num == 20 ,但你应该已经检查,如果j == 20 。 同时检查是否num % j == 0是超级的,因为当你到达那里时总是如此。

我也遇到了这个问题,并find了简单的解决scheme

 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 } 

这也适用于其他返回types,并提供最less的问题

我select的初始值是一个后退值,我可以根据需要多次重新赋值。

或简单地做这个东西:

 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; } else return false; } } 

看看这个。 它是C#中的三元运算符。

 bool BooleanValue = (num % 3 != 0) ? true : false; 

这只是为了表明原则; 您可以根据问号左侧的结果返回True或False(甚至是整数或string)。 好的运营商,这个。

一起三个select:

  public bool test1() { int num = 21; bool BooleanValue = (num % 3 != 0) ? true : false; return BooleanValue; } public bool test2() { int num = 20; bool test = (num % 3 != 0); return test; } 

甚至更短:

 public bool test3() { int num = 20; return (bool)(num % 3 != 0); } 

我喜欢打死马,但是我只想补充一点:

首先,问题在于你的控制结构的所有条件都没有得到解决。 从本质上讲,你是在说如果一个,那么这个,否则如果B,那么这个。 结束。 但是如果不是呢? 没有办法退出(即不是每个'path'返回一个值)。

我的另外一点是,这就是为什么你应该尽可能瞄准一个单一的出口的例子。 在这个例子中,你会做这样的事情:

 bool result = false; if(conditionA) { DoThings(); result = true; } else if(conditionB) { result = false; } else if(conditionC) { DoThings(); result = true; } return result; 

所以在这里,你总是一个return语句,这个方法总是在一个地方退出。 一些事情要考虑,但是…你需要确保你的退出值是有效的每条path或至less可以接受的。 例如,这个决策结构只有三种可能性,但是单一的退出也可以作为你的最终的陈述。 还是呢? 您需要确保最终返回值在所有path上都有效。 与5000万个出口点相比,这是一个更好的方法。

 class Program { double[] a = new double[] { 1, 3, 4, 8, 21, 38 }; double[] b = new double[] { 1, 7, 19, 3, 2, 24 }; double[] result; public double[] CheckSorting() { for(int i = 1; i < a.Length; i++) { if (a[i] < a[i - 1]) result = b; else result = a; } return result; } static void Main(string[] args) { Program checkSorting = new Program(); checkSorting.CheckSorting(); Console.ReadLine(); } } 

这应该工作,否则我得到错误,不是所有的codepaths返回一个值。 因此,我将结果设置为返回值,该值被设置为B或A,具体取决于哪个是true