Appearance
L1_04 程序基本语句
一、cin 语句
1.1 基本用法
cpp
#include <iostream>
using namespace std;
int main() {
int num;
cin >> num; // 从标准输入读取整数
return 0;
}1.2 读取多个数据
cpp
int a, b;
cin >> a >> b; // 连续读取两个整数1.3 读取字符串
cpp
string name;
cin >> name; // 读取一个单词(遇到空格结束)二、cout 语句
2.1 基本用法
cpp
#include <iostream>
using namespace std;
int main() {
cout << "Hello World!"; // 输出字符串
return 0;
}2.2 输出多个内容
cpp
int x = 10;
cout << "x = " << x << endl; // 输出变量值2.3 常用操作符
endl:换行符\n:换行\t:制表符
三、scanf 语句
3.1 基本用法
cpp
#include <cstdio>
int main() {
int num;
scanf("%d", &num); // 格式化输入
return 0;
}3.2 格式说明符
%d:整数%f:浮点数%c:字符%s:字符串
四、printf 语句
4.1 基本用法
cpp
#include <cstdio>
int main() {
printf("Hello World!\n"); // 格式化输出
return 0;
}4.2 格式化输出变量
cpp
int age = 18;
printf("年龄: %d\n", age);五、赋值语句
5.1 基本形式
cpp
变量 = 表达式;5.2 示例
cpp
int a = 10;
int b = a + 5;
b = b * 2;5.3 复合赋值
cpp
a += 5; // 等价于 a = a + 5
b -= 3; // 等价于 b = b - 3
c *= 2; // 等价于 c = c * 2
d /= 4; // 等价于 d = d / 4
e %= 3; // 等价于 e = e % 3六、复合语句
6.1 概念
用花括号 {} 包围的一组语句
6.2 示例
cpp
{
int x = 10;
int y = 20;
cout << x + y << endl;
}七、if 语句
7.1 基本形式
cpp
if (条件) {
// 条件为真时执行
}7.2 示例
cpp
int score = 85;
if (score >= 60) {
cout << "及格" << endl;
}八、switch 语句
8.1 基本形式
cpp
switch (表达式) {
case 值1:
// 代码
break;
case 值2:
// 代码
break;
default:
// 默认代码
break;
}8.2 示例
cpp
int day = 3;
switch (day) {
case 1:
cout << "星期一";
break;
case 2:
cout << "星期二";
break;
default:
cout << "其他";
break;
}九、for 语句
9.1 基本形式
cpp
for (初始化; 条件; 更新) {
// 循环体
}9.2 示例
cpp
for (int i = 0; i < 5; i++) {
cout << i << endl;
}十、while 语句
10.1 基本形式
cpp
while (条件) {
// 循环体
}10.2 示例
cpp
int i = 0;
while (i < 5) {
cout << i << endl;
i++;
}十一、do-while 语句
11.1 基本形式
cpp
do {
// 循环体
} while (条件);11.2 示例
cpp
int i = 0;
do {
cout << i << endl;
i++;
} while (i < 5);总结
掌握这些基本语句是编写程序的基础。通过组合使用这些语句,可以实现各种复杂的逻辑功能。
