简体   繁体   English

为什么第三个 if else 语句永远不会执行?

[英]Why does the third if else statement never gets executed?

Why does line 17 never gets executed.为什么第 17 行永远不会被执行。 I believe that it(if else statement) gets terminated as soon as it meets the first condition.我相信它(if else 语句)一旦满足第一个条件就会终止。 If so, how to solve this problem.如果是这样,如何解决这个问题。 Are there any way to check all of the conditions?有没有办法检查所有条件?

#include <iostream>
/*
Why does the third if else statement never gets executed. I believe that 
it(if else statement) gets terminated as soon as it meets the first
condition. If so, how to solve this problem. Are there any way to check
all of the conditions?
*/

int main() //This check if you can drive a car or not
{
    int age;
    std::cout << "Enter your age: ";
    std::cin >> age;

    if (age >= 18)
        std::cout << "You can drive.\n";
    else if (age < 18)
        std::cout << "You have to be 18 to drive.\n";
    else if (age >= 80) // 80 and above should not drive
        std::cout << "You are too old to drive\n";
    
    return 0;
}

Your first test is for age >= 18 .您的第一个测试是age >= 18 Any age above 18 will pass, and none of the subsequent else if tests will even be checked.任何超过18的人都可以通过,而随后的else if测试都不会被检查。 If you want this to work as intended, make sure to test age >= 80 first, so the next test only separates the groups below 80, eg:如果您希望它按预期工作,请确保首先测试age >= 80 ,以便下一个测试仅将 80以下的组分开,例如:

if (age >= 80)
    std::cout << "You are too old to drive\n";
else if (age < 18)
    std::cout << "You have to be 18 to drive.\n";
else  // Don't need a final if check; the previous two checks ensure if you get here, the age is between 18 and 79 inclusive
    std::cout << "You can drive.\n";

It won't ever reach the age >= 80 since a value that large would always meet the requirement of age >= 18 and the else tells it to only choose one option.它永远不会达到age >= 80 ,因为这么大的值总是满足age >= 18的要求,而else告诉它只选择一个选项。

You could check the over 80 condition first to make sure it gets found.您可以先检查 over 80 条件以确保找到它。

if (age >= 80) // 80 and above should not drive
    std::cout << "You are too old to drive\n";
else if (age >= 18)
    std::cout << "You can drive.\n";
else if (age < 18)
    std::cout << "You have to be 18 to drive.\n";

Or you could just add a condition to the first if statement so it won't apply to over 80.或者您可以只在第一个 if 语句中添加一个条件,这样它就不会应用于超过 80 个。

if (age >= 18 && age < 80)
    std::cout << "You can drive.\n";
else if (age < 18)
    std::cout << "You have to be 18 to drive.\n";
else if (age >= 80) // 80 and above should not drive
    std::cout << "You are too old to drive\n";

If age >= 18 is false, then age < 18 is true.如果age >= 18为假,则age < 18为真。

So, no matter what age is, the third if will never be reached.所以,不管是什么age ,第三个if永远都达不到。

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

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