C++ 学习操作基本之路(二)
一、条件语句
1. if 类型
if 类型就如上次我提到的逻辑语句 Exp1 ? Exp2 : Exp3
如果我想通过年龄来推荐的书籍,根据少不读《水浒》,老不读《三国》,可以这么表达:
#include <iostream>
using namespace std;
int main() {
// 输入年龄
int age;
cout << "please input your age" << endl;
cin >> age;
if(age < 18)
cout << "we recommend you to read ***Romance of Three Kingdoms***" << endl;
else
cout << "We recommend you to read ***Water Margin***" << endl;
return 0;
}
在这里 if 和 else 后面的花括号({})可以省略,因为只接一条语句,if 是可以hold 住的,但是如果后面有一大串就不行了。
如果我们嵌套 if 语句的话,再来男不读《西游》,女不读《红楼》,我们可以这么写
#include <iostream>
using namespace std;
int main() {
// 输入年龄
int age;
string gender;
cout << "please input your age and gender" << endl;
cin >> age, gender;
if(age < 18)
if(gender == "female")
cout << "we recommend you to read Romance of Three Kingdoms and Journey to the West" << endl;
else
cout << "we recommend you to read Romance of Three Kingdoms and Dreams of Red Chamber" << endl;
else
if(gender == "female")
cout << "we recommend you to read Water Margin and Journey to the West" << endl;
else
cout << "we recommend you to read Red Margin and Dreams of Red Chamber" << endl;
return 0;
}
这就是 if 函数的嵌套。
switch 类型
switch 主要表达是:
#include <iostream>
using namespace std;
int main() {
// input varable
int grade = 92;
// begin switch
switch(grade) {
// give a scope
case 90 ... 100:
cout << "Excellent, you can be the teacher next time" << endl;
break;
case 80 ... 89:
cout << "Gread, try to help those poor guys" << endl;
break;
case 70 ... 79:
cout << "Good, you can do better next time" << endl;
break;
case 60 ... 69:
cout << "well, you make contribution to the pass rate" << endl;
break;
case 0 ... 59:
cout << "Look forward to seeing you again!" << endl;
break;
default:
cout << "I can't get your idea, input again please" << endl;
}
return 0;
}
switch 主要出错的地方就是它的范围的写法,其实 "minimum … maximum ” 就好了,相当于 (a <= maximum && a >= minimum)。 第二,break 一定要加,不然会从头顺到尾。 第三,default 可省,作用和 else 差不多。然后记住哪里该缩进,哪里需要打冒号,这个比较重要。
以上就是条件语句的基本用法。我们下次见,嘻嘻。