章节概述
顺序结构是最基本的程序结构,按语句先后顺序依次执行。
虽然是基础,但涉及输入输出、变量声明、单位转换、整数除法、格式输出等重要基础。
核心原理
1. 程序执行模型
输入 → 计算 → 输出
C++ 程序从 main() 第一条语句开始,顺序执行到 return 0;
2. 整数运算规则
int a = 10, b = 3;
a / b // = 3 (向零取整)
a % b // = 1 (取余)
// 向上取整: (a + b - 1) / b // 等价于 ceil(a/b)
// 单位转换: int total = a * 10 + b; // 元和角统一为角3. 格式化输出
printf("%02d:%02d\n", h, m); // 前导零填充,宽度2
printf("%.2f\n", pi); // 保留2位小数4. 组合数计算 — 连续相除防溢出
C(n, 4) = n*(n-1)/2*(n-2)/3*(n-3)/4
先乘后除交替进行,保证中间结果为整数且避免溢出。
关键数据结构
- 无特殊数据结构需求(基础语法)
P1001 A+B Problem
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
cout << a + b << endl;
return 0;
}P1421 小玉买文具
题目: 班主任给小玉 a 元 b 角,每支铅笔 19 角,问最多能买多少支。
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int total = a * 10 + b;
cout << total / 19 << endl;
return 0;
}P5707 上学迟到
题目: 需要 s 分钟到校,8:00 前到,求最晚出发时间。
#include <cstdio>
int main() {
int s, v;
scanf("%d%d", &s, &v);
int t = (s + v - 1) / v + 10;
int total = 8 * 60 - t;
if (total < 0) total += 24 * 60;
printf("%02d:%02d\n", total / 60, total % 60);
return 0;
}P2181 对角线
题目: n 个顶点的凸多边形,任三线不共点,求对角线交点个数。即 C(n, 4)。
#include <iostream>
using namespace std;
int main() {
unsigned long long n;
cin >> n;
cout << n * (n - 1) / 2 * (n - 2) / 3 * (n - 3) / 4 << endl;
return 0;
}推荐练习题(洛谷)
相关技巧
多平台练习
| 洛谷 | 本题单 | 竞赛基础 |
| POJ (北大) | PKU JudgeOnline | 经典题目,适合巩固 |
| HDU (杭电) | HDU OJ | 暑期多校训练 |
| Codeforces | Codeforces | 国际竞赛,适合提升 |