C#编译器错误:“并非所有代码路径都返回值” [英] C# compiler error: "not all code paths return a value"

查看:105
本文介绍了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 。另一个明显的地方-在 if-else中添加一个 return 值的 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#编译器错误:“并非所有代码路径都返回值”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆