
上QQ阅读APP看本书,新人免费读10天
设备和账号都新为新人
1.4 人生就是不断地选择:if…else
在C++中,经常需要对一些条件做出判断,从而决定执行哪段代码,这时就需要使用选择结构语句。
1. if条件语句
if条件语句有三种语法格式,如下图所示。

(1)if语句——单分支结构,如下图所示。

(2)if…else语句——双分支结构,如下图所示。

(3)if语句的嵌套。在一个if语句中还可以包含一个或多个if语句,这叫作if语句的嵌套,如下图所示。

2. switch条件语句
除了if语句,switch条件语句也是一种常用的选择结构语句。和if条件语句不同,switch条件语句只能针对某个表达式的值做出判断,从而决定程序执行哪段代码。

注意,switch条件语句在执行完一个case之后不会自动停止,可以使用break语句停止;switch语句中的每一个case都必须是一个单独的值,该值必须是整数或字符,不能是浮点数。如果涉及取值范围、浮点数或比较,则先使用if…else转换。
训练1-5:输入一个学生的成绩score,判断是否及格。

训练1-6:输入一个学生的成绩score,判断其成绩等级(小于60为不及格,60~69为及格,70~79为中等,80~89为良好,90~100为优秀)。

训练1-7:输入一个年份,判断其是闰年还是平年(非整百年:能被4整除的为闰年。整百年:能被400整除的是闰年)。

训练1-8:输入一个整数,判断其是否为水仙花数。水仙花数是指一个3位数,它的各位数字的3次幂之和等于它本身。例如,3位数153是水仙花数,各位数字的立方和13+53+33= 153。

训练1-9:输入一个月份,判断该月份属于什么季节(在阳历中,3~5月为春季,6~8月为夏季,9~11月为秋季,12月至来年2月为冬季)。

