C#返回错误"不是所有code路径返回一个值" [英] c# returning error "not all code paths return a value"

查看:134
本文介绍了C#返回错误"不是所有code路径返回一个值"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写code,它返回一个给定的整数是否是或不是均匀地整除由1到20,但我不断收到错误CS0161:'ProblemFive.isTwenty(INT):不所有code路径返回一个值

请帮忙。

下面是我的code:

 公共静态布尔isTwenty(INT NUM)
{
    对于(INT J = 1; J< = 20; J ++)
    {
        如果(NUM引用%j!= 0)
        {
            返回false;
        }
        否则,如果(NUM引用%j == 0安培;试验#== 20)
        {
            返回true;
        }
    }
}


解决方案

您错过一个收益语句。

在编译器看你的code,这是看到了第三条路径(即其他你没有code代表)可能发生的,但没有按'T返回一个值。因此,不是所有code路径返回一个值

有关我的建议的修复,我把收益你的循环结束后。另一个明显的点 - 增加一个其他的有一个收益值到的if-else - 如果 - 将打破循环

 公共静态布尔isTwenty(INT NUM)
{
    对于(INT J = 1; J< = 20; J ++)
    {
        如果(NUM引用%j!= 0)
        {
            返回false;
        }
        否则,如果(NUM引用%j == 0安培;试验#== 20)
        {
            返回true;
        }
    }
    返回false; //这是你失踪声明
}

I'm trying to write code that returns whether or not a given integer is or is not divisible evenly by 1 to 20, but i keep receiving "error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value"

Please help.

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

解决方案

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
}

这篇关于C#返回错误&QUOT;不是所有code路径返回一个值&QUOT;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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