Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/loops/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 为什么我的if-else语句会滴落到第三个else?_C++_Loops_If Statement - Fatal编程技术网

C++ 为什么我的if-else语句会滴落到第三个else?

C++ 为什么我的if-else语句会滴落到第三个else?,c++,loops,if-statement,C++,Loops,If Statement,我试图了解这个控件语法是如何工作的 注意:这是我的int.main功能的一部分: while(cin >> Options){ if(Options == 1){ //If I enter '1' here it will output: "aHi.Else." cout << "a"; }else{ cout << "hi"; } if(Options == 2){ //If I enter '

我试图了解这个控件语法是如何工作的

注意:这是我的
int.main
功能的一部分:

while(cin >> Options){
    if(Options == 1){ //If I enter '1' here it will output: "aHi.Else."
        cout << "a";
    }else{
        cout << "hi";
    }
    if(Options == 2){ //If I enter '2' here it will output: "hiaElse."
        cout << "a";
    }else{
        cout <<"Hi.";
    }
    if(Options == 3){ //If I enter '3' here it will output: "hiHi.a"
        cout << "a";
    }else{
        cout << "Else." << endl;
    }
}
while(cin>>选项){
如果(Options==1){//如果我在这里输入'1',它将输出:“aHi.Else。”

cout如果
ifs
彼此不依赖,因此如果
Options
不是1,它将执行第一个
if
语句的else分支,即使Options是2或3。这同样适用于其他ifs。因为
Options
只能是1或2或3(或其他),您将始终获得另一个
if
s的
else
输出

如果要将多个条件相互链接,可以链接
else
if
。在下面的示例中,最后一个
else
仅在
Options
既不是1,也不是2,也不是3时执行

while(cin >> Options){
    if(Options == 1){
        cout << "a";
    }
    else if(Options == 2){
        cout << "b";
    }
    else if(Options == 3){
        cout << "c";
    }
    else{
        cout << "Hello";
    }
}

ifs
互不依赖,因此如果
Options
不是1,它将执行第一个
if
语句的else分支,即使Options是2或3。这同样适用于其他ifs。因为
Options
只能是1或2或3(或其他),您将始终获得另一个
if
s的
else
输出

如果要将多个条件相互链接,可以链接
else
if
。在下面的示例中,最后一个
else
仅在
Options
既不是1,也不是2,也不是3时执行

while(cin >> Options){
    if(Options == 1){
        cout << "a";
    }
    else if(Options == 2){
        cout << "b";
    }
    else if(Options == 3){
        cout << "c";
    }
    else{
        cout << "Hello";
    }
}

您希望这会做什么?为什么?使用
switch
语句;或表格查找。您可以使用
switch
语句,或将所有
else
更改为
else if(条件)
你希望它做什么,为什么?使用
开关
语句;或查表。你可以使用
开关
语句,或将所有
其他
更改为
其他,如果(条件)
非常感谢,这正是我要找的。非常感谢,这正是我要找的。