当我在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!";
*
* }
/*****************************************************/
"You are too small!"
。 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/