条件语句构成C++的分支结构,当程序走到条件语句时,会有几条不同的路走,从而在这里形成不同的分支。
常见的分支语句有if...else 与switch两种
1、
if(判断条件)
yi;
else
er;
如果判断条件成立,程序会执行yi这一部分内容,否则(也就是判断条件不成立),就会执行er这部分内容。
例如:
#include <iostream>
using namespace std;
int main(){
int a;
cin>>a;
if(a>6)
cout<<"Hello, everyone. Welcome to the earth!"<<endl;
else
cout<<"Hi, ladies and gentlemen, welcome to the great land!";
return 0;
}
2、switch()是一种多路分支结构,可以分成大于2个的不同路径。
#include <iostream>
using namespace std;
int main(){
int a; cin>>a;
switch(a){
case 1: cout<<"The first choice, please!"<<endl; break;
case 2: cout<<"The second choice, please!"<<endl; break;
case 3: cout<<"The third choide, please!"<<endl; break;
default:cout<<"Sorry, we don't have your choice. Maybe someone else has it.";
}
return 0;
}
其中,default 是所有情况之外的一种情况,如果前面的情况都不是选择的情况,那么执行这个默认的情况。当然,default可以存在,也可以不存在。。。。
每种情况后面都有一个break, 若没有,那么执行完这个情况,会自动进入下一个情况,而不是跳出switch结构。