1.ifelse语句
(1)简单使用
if(条件1){
代码块1;
}else{
代码块2;
}
例子:
判断字符是否合法:
#include <iostream>
using namespace std;
int main()
{
char pan='\0';//初始设为空
cout<<"请输入一个字符来判断是否合法"<<endl;
cin>>pan;
if(pan>='A'&&pan<='Z')
{
cout<<"是合法盘符!"<<endl;
}else{
cout<<"不是合法盘符!"<<endl;
}
return 0;
}
(2)多重if
对应的ifelse:
if(条件1){
代码块1;
}else if(条件2){
代码块2;
}else{
代码块3;
}
例子:
#include <iostream>
using namespace std;
int main()
{
double flowerPrice=3000;
cout<<"这花多少钱?"<<endl;
cout<<"小男生:";
if(flowerPrice >= 50000){
cout<<"非常贵"<<endl;
}else if(flowerPrice >= 500){
cout<<"贵"<<endl;
}else if(flowerPrice >= 50){
cout<<"便宜"<<endl;
}
return 0;
}
2.switch语句
格式:
switch(表达式)
{
case 常量1:
语句1;
break;
case 常量2:
语句2;
break;
default:
语句;
}
注意问题:
- switch后的表达式只能是整型或字符型
- case后常量表达式的值不能相同
- case后允许多条语句,不需要大括号
- 如果不添加break语句,需要特别注意执行顺序。
- 如果没有break就不会跳出,会一直向下执行知道switch语句执行完成。
- case和default子句的先后顺序可以自行变动
- default子句可以省略
例子:
#include <iostream>
using namespace std;
int main()
{
int choice =12345;
switch(choice)
{
case 1:
cout<<1<<endl;
break;
case 2:
cout<<2<<endl;
break;
case 3:
cout<<3<<endl;
break;
default:
cout<<998<<endl;
break;
}
return 0;
}
3.switch和多重if对比
相同点:都是用来处理多条分支语句的。
不同点:
switch :等值条件判断条件是有限个的时候
多重if :判断某个连续区间时的情况(杀牛刀)
实例:月份天数:
#include <iostream>
using namespace std;
int main()
{
int month=12;
int year;
cin>>year>>month;
switch(month)
{
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
cout<<"31天"<<endl;
break;
case 4:
case 6:
case 9:
case 11:
cout<<"30天"<<endl;
break;
case 2:
if(year%4==0)
cout<<"29天"<<endl;
else
cout<<"28天"<<endl;
break;
}
return 0;
}