第6课:分支语句和逻辑运算符
教你的程序学会思考和选择!就像在人生的十字路口,选择不同的路,看到不同的风景。
环节一:If...Else:道路的岔口
程序执行到这里,需要根据一个条件来决定接下来走哪条路。
过桥抉择
过桥需要10个金币。输入你拥有的金币,看看小车会走哪条路?
🌉 走大桥
🏞️ 走小路
🚗
代码解读
#include <iostream>
using namespace std;
int main() {
int score;
cout << "请输入你的分数:";
cin >> score;
if (score >= 90) { // 测试条件
cout << "你获得了优秀!" << endl;
} else if (score >= 60) {
cout << "你合格了。" << endl;
} else {
cout << "你需要努力了。" << endl;
}
return 0;
}
环节二:逻辑运算符:条件组合器
有时候,我们需要同时判断多个条件才能做决定。逻辑运算符就是我们的好帮手!
代码解读
#include <iostream>
using namespace std;
int main() {
int age;
cout << "请输入你的年龄: ";
cin >> age;
// 使用 && 设置取值范围
if (age >= 10 && age <= 15) {
cout << "你处于初级学习阶段。" << endl;
}
char choice;
cout << "请选择 [Y]或[N]: ";
cin >> choice;
// 使用 || 检查大写或小写
if (choice == 'y' || choice == 'Y') {
cout << "你选择了‘是’。" << endl;
}
return 0;
}
打开保险箱
带了钥匙?
知道密码?
🔐
环节三:Switch语句:魔法电梯
当你需要根据一个变量的多个不同值,选择不同的操作时,Switch就像一部可以直达目的楼层的电梯。
电梯控制面板
按下按钮,看看电梯会带我们去哪一楼?
3F: 🐱
2F: 🐶
1F: 🤖
代码解读
#include <iostream>
using namespace std;
int main() {
char choice;
cout << "选择颜色: R (红), B (蓝): ";
cin >> choice;
switch (choice) {
case 'r':
case 'R':
cout << "你选择了红色。" << endl;
break; // 停止,跳出switch
case 'b':
case 'B':
cout << "你选择了蓝色。" << endl;
break;
default: // 如果不匹配任何case
cout << "选择无效。" << endl;
}
return 0;
}
魔法师的挑战
是时候检验你的学习成果了!尝试完成下面的任务吧。
练习 1:温度建议
任务:
编写一个程序,要求用户输入当前温度。如果温度大于30度,建议“开空调”;如果在10到30度之间,建议“穿T恤”;否则建议“穿外套”。
点击查看参考答案
#include <iostream>
using namespace std;
int main() {
int temp;
cout << "请输入当前温度(摄氏度): ";
cin >> temp;
if (temp > 30) {
cout << "温度太高了,请开空调!" << endl;
} else if (temp >= 10 && temp <= 30) {
cout << "温度适中,穿T恤即可。" << endl;
} else {
cout << "温度很低,请穿外套。" << endl;
}
return 0;
}
练习 2:字符类型统计
任务:
编写一个程序,要求用户输入一行字符,直到遇到句号(.)为止。程序应报告输入的字符中,有多少个是字母,有多少个是数字。
点击查看参考答案
#include <iostream>
#include <cctype>
using namespace std;
int main() {
char ch;
int letter_count = 0;
int digit_count = 0;
cout << "请输入一行字符(以句号结束):" << endl;
while (cin.get(ch) && ch != '.') {
if (isalpha(ch)) {
letter_count++;
} else if (isdigit(ch)) {
digit_count++;
}
}
cout << "字母数量: " << letter_count << endl;
cout << "数字数量: " << digit_count << endl;
return 0;
}
练习 3:简单的文件统计
任务:
编写程序,让用户输入3个整数,并将这3个数字写入到一个名为 `numbers.txt` 的文件中。
点击查看参考答案
#include <iostream>
#include <fstream>
using namespace std;
int main() {
int num1, num2, num3;
ofstream outFile;
cout << "请输入三个整数:" << endl;
cin >> num1 >> num2 >> num3;
outFile.open("numbers.txt");
if (!outFile.is_open()) {
cout << "错误:无法创建文件" << endl;
return 1;
}
outFile << num1 << endl;
outFile << num2 << endl;
outFile << num3 << endl;
outFile.close();
cout << "数据已保存到 numbers.txt" << endl;
return 0;
}