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

C# compiler error: quot;not all code paths return a valuequot;(C# 编译器错误:“并非所有代码路径都返回值;)

本文介绍了C# 编译器错误:“并非所有代码路径都返回值";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

错误 CS0161:ProblemFive.isTwenty(int)":并非所有代码路径都返回值

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

这是我的代码:

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

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

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.

对于我建议的修复,我在循环结束后放置了一个 return.另一个明显的地方 - 将具有 return 值的 else 添加到 if-else-if - 会破坏 for 循环.

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
}

这篇关于C# 编译器错误:“并非所有代码路径都返回值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C# 编译器错误:“并非所有代码路径都返回值";