c++ - c++多个if语句。为什么其他语句也会执行?

标签 c++ conditional-statements

当我在else语句之前执行if语句时,代码将正确执行。但是,当我执行远离else语句的if语句时,c++将执行所选的“if语句”,但还将执行“else语句”。那里发生了什么事?
我知道如何修复我的代码,而无需else语句执行问题。
我只想知道当我放置两个或多个if语句和else语句时c++的作用或流程的工作方式。如果if语句已经执行,为什么else语句执行?
例如下面的代码:
如果输入的值小于160,则第一个if语句将执行,而else语句也将在其后执行。

#include <iostream>
using namespace std;

int main()
{

    float h;

    cout << "What is your height in centimeters?";
    cin >> h;
    if (h <= 160) {
        cout << "You are too small!";
    }
    if (h >= 190) {
        cout << "You are too tall!";
    }
    else {
        cout << "You have the appropriate height. You are qualified!";
    }
}

最佳答案

the c++ will execute the chosen 'if statement' but the 'else statement' will also execute. What is happening there?


这两个if语句是分开的,并且else是第二个if语句的一部分:
/* One if statement block  ************************/
 *       if(h<=160){
 *          cout << "You are too small!";
 *            
 *        }
/*************************************************/

/* Second if Statement block, "else" is part of it. Only one of them can be true */
 *        if(h>=190){ 
 *            cout << "You are too tall!";
 *            
 *        }
 *        else{ 
 *            cout << "You have the appropriate height. You are qualified!";
 *            
 *        }
/*****************************************************/
  • 如果 h小于160,则第一个语句为 true ,您将在输出中看到"You are too small!"
  • 如果选中,则检查第二个,如果第一个为 true ,则第二个显然是 false ,因为h小于160。如果是 false ,则将执行else块。

  • 每当你写:
    if (...)  {}
    else  {}
    
    执行以上操作之一,即if块或else块。
    注意,还有else if语句,您可以像这样使用它:
        if (h <= 160) {  //1st check
            cout << "You are too small!";
        }
        else if (h >= 190) { //second check
            cout << "You are too tall!";
        }
        else { //third
            cout << "You have the appropriate height. You are qualified!";
        }
    
    现在,这三个是一项条件检查的一部分。一次只能运行其中一个。

    关于c++ - c++多个if语句。为什么其他语句也会执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63299544/

    相关文章:

    c++ - 使用OpenCV 2.4.3在Visual C++中读取/写入图像时出错

    c++ - fopen 或 fstream 等是否会意外破坏文件 C/C++

    php - 制作条件语句以发送电子邮件警报

    java - Java 中 Do..While 循环的多个条件

    r - 在 R 中编写一个包含 if/else 语句和 rowSums() 的函数,定义如何处理 NA

    xml - WiX - 如何仅在 XML 元素尚不存在时添加它

    c++ - Visual Studio C++ 从字符串中删除最后一个字符

    c++ - const std::shared_ptr<const T> 作为函数的参数最终会改变智能指针中类的值

    c++ - 为什么变量指针包含相同数据类型的地址?

    flutter - 如果Dart/Flutter中onPressed()属性中的其他条件问题