首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >控制路径不返回值3

控制路径不返回值3
EN

Stack Overflow用户
提问于 2014-04-12 09:05:49
回答 2查看 29关注 0票数 0

它给了我一个错误,说并不是所有的控制路径都返回值:请帮助。

代码语言:javascript
复制
int using_range()
{
    int Num;

    try{
        cout << "Please enter a integer between 1 and 10: ";
        cin >> Num;
        if ((Num > 10) || (Num < 0)){
            throw 77;
        }
        else if ((Num <= 10) || (Num >= 0)){
            cout << Num << " is in range\n";
            return 0;
            system("pause");
        }
    }
    catch (int x){
        cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
        system("pause");
        return 0;
    }
}

我不知道该怎么做

EN

回答 2

Stack Overflow用户

发布于 2014-04-12 09:07:45

问题是您有一个后跟else ifif,但是如果这两个检查都失败了,那么默认情况下将不会返回任何内容。您的代码应该防止这种情况发生,但是编译器不够聪明,无法100%确定您永远不会在两个if检查中都失败。

代码语言:javascript
复制
try{
    cout << "Please enter a integer between 1 and 10: ";
    cin >> Num;
    if ((Num > 10) || (Num < 0)){
        throw 77;
    }
    else if ((Num <= 10) || (Num >= 0)){
        cout << Num << " is in range\n";
        return 0;
        system("pause");
    }
    // <- if you get here, nothing is going to be returned
 }

另一种方法可能是将else if更改为只使用else

票数 0
EN

Stack Overflow用户

发布于 2014-04-12 09:39:34

所以,简单解释一下:当你有一个需要返回值的函数(在你的例子中,是一个int),当你的程序中的所有路径都这样做时,编译器会很高兴。在这段代码中,可能会出现这样一种情况,即它可能会越过您的ifelse if,在这种情况下,它不会做任何事情。如果你愿意,你可以在这里抛出一个错误或者别的什么。

但我还想添加一件额外的事情,那就是在接收用户输入时添加一些保护。也就是说,确保用户输入了一个数字!

例如,目前,如果用户输入b,则输出将是0 is in range

因此,添加另一个检查以确保:

代码语言:javascript
复制
int using_range()
{
    int Num;

    try{
        cout << "Please enter a integer between 1 and 10: ";
        cin >> Num;

        // this checks if whatever the user input can be parsed as an int.
        if (!cin){
           cout << "please enter a number." << endl;
           return -1;
        }
        else if ((Num > 10) || (Num < 0)){
            throw 77;
        }
        else if ((Num <= 10) || (Num >= 0)){
            cout << Num << " is in range\n";
            return 0;
            system("pause"); // also, this will never happen :)
        }
        else{
            // not sure how it could get here, but maybe in weird corner cases?
            return -1;
        }
    }
    catch (int x){
        cout << "The number cannot be greater than 10, or less than zero. Error " << x << endl;
        system("pause");
        return 0;
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23024860

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档