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

查看:65
本文介绍了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 值的 elseif-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天全站免登陆