0%

C++中的选择选择语句

一、if条件语句

作用:执行满足条件的语句

if语句的三种形式

  • 单行格式if语句
  • 多行格式if语句
  • 多条件的if语句

1.单行格式if语句

语法:if(条件){条件满足时执行的语句}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;

int main()
{
int score;
cin>>score;
if(score>500)//注意此处没有;
{

cout<<"考得不错"<<endl;

}


return 0;
}

2.多行格式if语句

语法:if(条件){条件满足时执行的语句}else{条件不满足是执行的语句};

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include<iostream>
using namespace std;

int main()
{
int score;
cin>>score;

if(score>500)
{
cout<<"考得不错"<<endl;
}
else
{

cout<<"继续加油吧"<<endl;
}




return 0;
}

3.多条件的if语句

语法:if(条件1){条件1满足时执行的代码}else if(条件2){条件2满足时执行的代码} ... else{以上条件都不满足执行的语句}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include<iostream>
using namespace std;

int main()
{
int score;
cin>>score;

if(score>500)//第一个条件
{
cout<<"考得不错"<<endl;
}
else if(score>400)//第二个条件
{
cout<<"考得还行"<<endl;
}
else if(score>300)//第三个条件
{
cout<<"考得有点差"<<endl;
}
else
{

cout<<"继续加油吧"<<endl;
}



return 0;
}

4.嵌套if语句

if语句里面还有if语句

注意if嵌套语句中条件的大小顺序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include<iostream>
using namespace std;

int main()
{
int score;
cin>>score;

if(score>500)
{
cout<<"考得不错"<<endl;//此处判断条件要从大到小,否则无法正常运行
if(score>650)
{
cout<<"有望985"<<endl;
}
else if(score>600)
{
cout<<"有望211"<<endl;
}
else
{
cout<<"有望一本"<<endl;
}
}

else
{

cout<<"继续加油吧"<<endl;
}




return 0;
}

二、三目运算符

作用:通过三目运算符实现简单的判断

语法:条件 ? 代码1 : 代码2

解释:

如果满足条件,则执行代码1,否则执行代码2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include<iostream>
using namespace std;

int main()
{
int a,b,c;
cin>>a>>b;//注意此处为>>而不是,

c=(a>b?a:b);

cout<<c<<endl;

(a>b?a:b)=50;//三目运算符同样可以这样使用,表示将a b中较大的一个赋值为50
cout<<a<<"\n"<<b<<endl;

return 0;
}

三、switch条件语句

作用:执行多条件分支语句

语法:

1
2
3
4
5
6
7
8
9
10
11
12
switch(表达式)

{
case 结果1:执行语句;break;

case 结果2:执行语句;break;

...

default:执行语句;break;

}

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
using namespace std;

int main()
{
int a;
cin>>a;
switch(a)
{
case 8:
cout<<"prefect"<<endl;
break;//此处一定不要忘记break
case 5:
cout<<"normal"<<endl;
break;
default:
cout<<"bad"<<endl;
break;


}


return 0;

}

注意:

switch缺点:判断时只能是整型或者字符型,不可以是区间,而if可以

switch有点:结构清晰,执行效率高