繁体   English   中英

如何使用2个数字之间的数字使“if”语句成立? C ++

[英]How can I make an “ if ” statement true using a number in-between 2 numbers? C++

在我看来,我觉得很多人对这个问题感到困惑。 我想要做的是询问用户一个数字,如果它在0到17之间,我希望它的输出是:

Too Young

如果它是18 - 42,输出应该是:

Adult

如果它是43岁以上:

Senior

一直使用switch语句

这是我使用的代码:

#include <iostream>
using namespace std;

int main()
{
    int age;
    cin >> age;
    if (age <= 16) {
        cout <<"Too young";
    }
    if (age <= 42) {
        cout << "Adult";
    }
    if (age <= 70) {
        cout << "Senior";
    }

    return 0;
}

我的代码输出是:

Too YoungAdultSenior

请帮帮我。

将代码替换为:

#include <iostream>
using namespace std;

int main()
{
    int age;
    cin >> age;
    if (age <= 17) {
        cout <<"Too young";
    } else if (age <= 42) {
        cout << "Adult";
    } else {
        cout << "Senior";
    }

    return 0;
}

要检查是否某物是在同一时间2度的条件下,使用&&操作者,这意味着and并检查两个条件为真任一侧上。 年龄介于44 and 56之间的示例:

#include <iostream>

int main()
{
    int age=55;
    if ((age>=44) && (age <= 56))
    {
       std::cout << "YAY!!!\n";
    }
    return 0;
}

在C ++ 11中 - 您可以使用and关键字代替&&

在上面的答案中,如果你想using namespace std; ,只需使用这段代码:

#include <iostream>
using namespace std;

int main()
{
    int age;
    cin >> age;
    if ((age>=44) && (age <= 56))
    {
       cout << "YAY!!!\n";
    }
    return 0;
}

这是你用switch语句btw做的方法:

#include <iostream>
using namespace std;

int main(){

    int age;
    cin >> age;

    switch (age) {
        case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17:
            cout << "Too young\n";
            break;
        case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 29: case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37: case 38: case 39: case 40:
            cout << "Adult\n";
            break;
        default:
            cout << "Senior\n";

    }

    return 0;
}

完美的方式: -

#include <iostream>
using namespace std;

int main()
{
    int age;
    cin >> age;
    if (age < 18 && age >=0) {
        cout <<"Too young";
    } else if (age >= 18 && age <= 42) {
        cout << "Adult";
    } else if(age > 42)
        cout << "Senior";
    }

    return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM