doc/notebook/docs/NOI竞赛大纲/二.C++程序设计/3.程序基本语句.md

192 lines
3.3 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 3. 程序基本语句
程序语句是构成程序逻辑的核心部分,掌握基本语句的使用,是编程入门的关键。本章将系统讲解输入输出、条件判断、循环结构等常用语句。
---
## 【2】输入输出语句与赋值语句
### ✅ cin 和 coutC++ 风格)
```cpp
#include <iostream>
using namespace std;
int main() {
int a;
cin >> a; // 输入一个整数
cout << "你输入的是: " << a << endl;
return 0;
}
```
- `cin >>`:从键盘读取输入。
- `cout <<`:输出内容到屏幕。
- `<< endl`:换行输出。
---
### ✅ scanf 和 printfC 风格)
```cpp
#include <stdio.h>
int main() {
int a;
scanf("%d", &a); // 输入一个整数
printf("你输入的是: %d\n", a);
return 0;
}
```
- `%d` 表示格式化整数,`&a` 是地址符,表示把输入值存入变量 a。
---
### ✅ 赋值语句
```cpp
int x;
x = 10;
```
- 把右边的表达式结果赋值给左边的变量。
---
### ✅ 复合语句(代码块)
```cpp
{
int a = 5;
int b = 6;
cout << a + b << endl;
}
```
- 大括号 `{}` 包裹的是复合语句,表示多个语句作为一个整体执行。
---
## 【2】条件语句选择结构
### ✅ if 语句
```cpp
int score = 85;
if (score >= 60) {
cout << "及格" << endl;
}
```
### ✅ if-else 语句
```cpp
if (score >= 90) {
cout << "优秀" << endl;
} else {
cout << "继续努力" << endl;
}
```
### ✅ 多层 if-else
```cpp
if (score >= 90) {
cout << "优秀";
} else if (score >= 75) {
cout << "良好";
} else if (score >= 60) {
cout << "及格";
} else {
cout << "不及格";
}
```
---
### ✅ switch 语句
```cpp
int option = 2;
switch(option) {
case 1:
cout << "选项一";
break;
case 2:
cout << "选项二";
break;
default:
cout << "无效选项";
}
```
- `switch` 适用于整型、字符型变量。
- 每个 `case` 后面用 `break` 防止穿透执行。
---
## 【2】循环语句重复结构
### ✅ for 循环
```cpp
for (int i = 0; i < 5; i++) {
cout << i << " ";
}
```
- 固定次数循环,通常用于计数。
---
### ✅ while 循环
```cpp
int i = 0;
while (i < 5) {
cout << i << " ";
i++;
}
```
- 先判断再执行,适用于条件满足才循环的情况。
---
### ✅ do while 循环
```cpp
int i = 0;
do {
cout << i << " ";
i++;
} while (i < 5);
```
- 至少执行一次,再判断条件。
---
## 【3】多层循环语句
### ✅ 二重循环示例:九九乘法表
```cpp
for (int i = 1; i <= 9; i++) {
for (int j = 1; j <= i; j++) {
cout << j << "*" << i << "=" << i * j << "\t";
}
cout << endl;
}
```
- 外层控制行数,内层控制列数。
- 多层嵌套常用于处理二维数据(如矩阵、图形、表格等)。
---
### ✅ 实际应用:输出矩阵所有元素
```cpp
int matrix[2][3] = {
{1, 2, 3},
{4, 5, 6}
};
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 3; j++) {
cout << matrix[i][j] << " ";
}
cout << endl;
}
```
---
## ✅ 小结
- `cin/cout``scanf/printf` 是基础输入输出方式。
- `if`、`switch` 用于做出选择。
- `for`、`while`、`do while` 是常用循环方式。
- 多层嵌套循环用于复杂数据结构处理。
- 编写循环时要注意终止条件,防止死循环。