C#编译器错误:“并非所有代码路径都返回值”

发布于 2025-02-03 21:09:52 字数 432 浏览 7 评论 0原文

我正在尝试编写代码,以返回给定整数是否可以平均1到20分,但我不断收到以下错误:

错误cs0161:'QUASSIONFIVE.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;
        }
    }
}

I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20,
but I keep receiving the following error:

error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value

Here is my code:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

淡忘如思 2025-02-10 21:09:52

您缺少返回语句。

当编译器查看您的代码时,它会看到可能发生但不会返回值的第三个路径(else您未代码)。因此,并非所有代码路径返回值

对于我建议的修复程序,我在循环结束后放置了返回。另一个明显的位置 - 添加返回值的 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
}

You're missing a return statement.

When the compiler looks at your code, it's sees a third path (the else you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value.

For my suggested fix, I put a return after your loop ends. The other obvious spot - adding an else that had a return value to the if-else-if - would break the for loop.

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
}
风吹雪碎 2025-02-10 21:09:52

编译器在循环的最后一次迭代中没有获得复杂的逻辑,因此它认为您可以退出循环,最终根本不返回任何内容。

与其在最后一次迭代中返回,只需在循环之后返回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是否过多,因为到达那里时始终是正确的。

The compiler doesn't get the intricate logic where you return in the last iteration of the loop, so it thinks that you could exit out of the loop and end up not returning anything at all.

Instead of returning in the last iteration, just return true after the loop:

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

Side note, there is a logical error in the original code. You are checking if num == 20 in the last condition, but you should have checked if j == 20. Also checking if num % j == 0 was superflous, as that is always true when you get there.

你列表最软的妹 2025-02-10 21:09:52

我还遇到了这个问题,发现它的简单解决方案

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
}

也与其他返回类型一起使用,并且给出了最少的问题,

我选择的初始值是倒下的价值,我能够多次重新分配该值根据需要。

I also experienced this problem and found the easy solution to be

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
}

This also works with other return types and gives the least amount of problems

The initial value I chose was a fall-back value and I was able to re-assign the value as many times as required.

浪漫人生路 2025-02-10 21:09:52

我喜欢击败死马,但我只是想提出一个额外的观点:

首先,问题是您控制结构的所有条件都已经解决。本质上,您是说如果A,则是否,如果B,则是。结尾。但是,如果两者都不呢?没有办法退出(即,不是每个“路径”返回值)。

我的其他观点是,这是为什么您应该在可能的情况下进行一次出口的一个例子。在此示例中,您将做类似的事情:

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

return result;

因此,在这里,您将始终有一个返回语句,并且该方法始终在一个地方退出。不过,有几件事要考虑...您需要确保您的退出价值在每条路径上都是有效的,或者至少可以接受。例如,这种决策结构仅说明了三种可能性,但是单个退出也可以充当您的最终语句。还是这样?您需要确保最终返回值在所有路径上都是有效的。这是一种更好的方法,可以使用5000万个出口点。

I like to beat dead horses, but I just wanted to make an additional point:

First of all, the problem is that not all conditions of your control structure have been addressed. Essentially, you're saying if a, then this, else if b, then this. End. But what if neither? There's no way to exit (i.e. not every 'path' returns a value).

My additional point is that this is an example of why you should aim for a single exit if possible. In this example you would do something like this:

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

return result;

So here, you will always have a return statement and the method always exits in one place. A couple things to consider though... you need to make sure that your exit value is valid on every path or at least acceptable. For example, this decision structure only accounts for three possibilities but the single exit can also act as your final else statement. Or does it? You need to make sure that the final return value is valid on all paths. This is a much better way to approach it versus having 50 million exit points.

三生殊途 2025-02-10 21:09:52

或只是做这些事情:

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

Or simply do this stuff:

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; 
      }
   }
}
悲欢浪云 2025-02-10 21:09:52

看看这个。它是C#中的三元操作员。

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

这只是为了显示原则。您可以根据问号左侧的结果的结果返回真或错误(甚至整数或字符串)。不错的操作员,这个。

在一起三个替代方案:

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

Have a look at this one. It is the Ternary operator in C#.

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

This is just to show the principle; you can return True or False (or even integer or string) depending on the outcome of something on the left side of the question mark. Nice operator, this.

Three alternatives together:

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

Even Shorter:

public bool test3()
{
    int num = 20;
    return (bool)(num % 3 != 0);
}
彻夜缠绵 2025-02-10 21:09:52
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();
    }
}

这应该有效,否则我会发现并非所有编码器都返回值的错误。因此,我将结果设置为返回值,该值将其设置为B或A

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

This should work, otherwise i got the error that not all codepaths return a value. Therefor i set the result as the returned value, which is set as either B or A depending on which is true

心凉怎暖 2025-02-10 21:09:52

例如,如果我放错了返回语句,通常会发生这种情况,例如:

添加返回语句,或者在我的情况下,将其移动到纠正范围将可以解决:

This usually happens to me if I misplace a return statement, for example:
enter image description here

Adding a return statement, or in my case, moving it to correct scope will do the trick:
enter image description here

梦途 2025-02-10 21:09:52

并非所有代码路径都返回值。

解决方案:要解决错误,请确保从函数中的所有代码路径返回一个值,或将noimplitiriturns设置为tsconfig.json文件中的false。

Not all code paths return a value.

Solution: To solve the error, make sure to return a value from all code paths in the function or set noImplicitReturns to false in your tsconfig.json file.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文