C++ 基础教程:从 For 循环到算法初步
系统介绍了 C++ 编程语言的基础知识与常用算法。内容涵盖 for 与 while 循环结构、函数模块化设计、结构体定义与嵌套、字符串处理、ASCII 码应用。深入讲解了递归原理、回溯法模板及高精度整数加减法的模拟实现。通过斐波那契数列、数根计算、全排列枚举等经典例题,帮助读者掌握 C++ 核心语法与算法思维,适合编程初学者入门与巩固。

系统介绍了 C++ 编程语言的基础知识与常用算法。内容涵盖 for 与 while 循环结构、函数模块化设计、结构体定义与嵌套、字符串处理、ASCII 码应用。深入讲解了递归原理、回溯法模板及高精度整数加减法的模拟实现。通过斐波那契数列、数根计算、全排列枚举等经典例题,帮助读者掌握 C++ 核心语法与算法思维,适合编程初学者入门与巩固。

for (int i = 1; i <= n; i++) {
// 定义计数变量,判断结束条件,执行动作
}
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
int cnt = 0;
for (int i = 1; i <= n; i++) {
cnt++;
}
cout << cnt;
return 0;
}
#include <iostream>
using namespace std;
long long a[55];
int fbnq(int n) {
a[1] = 1, a[2] = 1;
for (int i = 3; i <= n; i++) {
a[i] = a[i - 1] + a[i - 2];
}
return a[n];
}
int main() {
int n;
cin >> n;
cout << fbnq(n);
return 0;
}
| 函数类型 | 特点 | 用法 |
|---|---|---|
| int | 返回值为 int 类型 | int 函数名 (int 参数名) |
| long long | 返回值为 long long 类型 | long long 函数名 (long long 参数名) |
| bool | 返回值类型为 bool | bool 函数名 (bool 参数名) |
| void | 无返回值 | void 函数名 (参数名) |
练习题目:
题目描述 计算花费。输入重量 w,若 w<=1 则花费 13;否则花费 13 + ceil((w-1)/0.5)。
代码实现
#include <cstdio>
#include <cmath>
using namespace std;
int express(double w) {
w = round(w * 10) / 10;
if (w <= 1) {
return 13;
} else {
double temp = ceil((w - 1) / 0.5);
return 13 + (int)temp;
}
}
int main() {
double w;
scanf("%lf", &w);
printf("%d\n", express(w));
return 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
// 可叠层使用
}
}
题目描述 给定三种饲料的营养成分及需求,求满足需求的饲料组合数量。
代码实现
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long LL;
int main() {
int a, b, c;
cin >> a >> b >> c;
int a1, b1, c1;
cin >> a1 >> b1 >> c1;
int a2, b2, c2;
cin >> a2 >> b2 >> c2;
int a3, b3, c3;
cin >> a3 >> b3 >> c3;
for (int i = 0; i < 100; i++) {
for (int j = 0; j < 100; j++) {
for (int k = 0; k < 100; k++) {
if (!i && !j && !k) continue;
int x = a1 * i + a2 * j + a3 * k;
int y = b1 * i + b2 * j + b3 * k;
int z = c1 * i + c2 * j + c3 * k;
if (x * b == y * a && y * c == b * z && x % a == 0) {
cout << i << " " << j << " " << k << " " << x / a << endl;
return 0;
}
}
}
}
cout << "NONE";
return 0;
}
while (true) {
// 条件成立时继续运行
}
题目描述 将一个数的各位数字相加,若结果不是一位数则重复此过程,直到得到一位数。
输入描述 一个整数 n (1 <= n <= 10^9)
输出描述 一个数字,即 n 的数根
样例 输入:39 输出:3
在 C++ 中,结构体默认访问权限为 public。
#include <iostream>
#include <string>
using namespace std;
struct Student {
string name;
int age;
float score;
};
int main() {
Student stu1;
stu1.name = "张三";
stu1.age = 20;
stu1.score = 85.5;
cout << "姓名:" << stu1.name << endl;
cout << "年龄:" << stu1.age << endl;
cout << "成绩:" << stu1.score << endl;
return 0;
}
// 方式 1:普通定义
struct Person {
string name;
int age;
};
// 方式 2:定义时创建对象
struct Car {
string brand;
} car1;
// 方式 3:使用 typedef
typedef struct {
string city;
int number;
} Address;
struct Student {
string name;
int age;
float score;
};
int main() {
// 聚合初始化
Student stu1 = {"张三", 20, 85.5};
// 指定成员初始化
Student stu2 = {.name = "李四", .age = 21, .score = 92.0};
// 默认初始化
Student stu4{};
return 0;
}
struct Address {
string city;
string street;
int number;
};
struct Student {
string name;
Address addr;
};
int main() {
Student stu = {"张三", {"北京", "长安街", 1}};
return 0;
}
struct Rectangle {
double width;
double height;
double area() { return width * height; }
};
void printRect(const Rectangle &r) {
cout << r.width << " " << r.height << endl;
}
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
struct Student {
string id;
string name;
int age;
double score;
void display() const {
cout << "学号:" << id << ",姓名:" << name << endl;
}
};
struct Class {
string className;
vector<Student> students;
void addStudent(const Student& stu) {
students.push_back(stu);
}
void showAll() {
for (const auto& stu : students) {
stu.display();
}
}
};
int main() {
Class c1 = {"计算机 1 班"};
c1.addStudent({"2024001", "张三", 20, 85.5});
c1.showAll();
return 0;
}
ASCII 码是字符的数字表示。char 类型可转换为 int 获取其 ASCII 值。
#include <iostream>
using namespace std;
int main() {
char s = 'A';
int a = s;
cout << a; // 输出 65
return 0;
}
注意:'A'-'Z' 连续,'a'-'z' 连续,但大小写之间不连续。
C++ 中的 string 类型支持下标操作,但不支持负索引。
string s = "作者";
string n = "真帅";
string m = s + n;
题目描述 有 N 只史莱姆排成一排,颜色用英文小写字母表示。相同颜色的相邻史莱姆会融合。问最后剩下几只?
代码实现
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
string s;
cin >> s;
int count = 1;
for (int i = 1; i < n; i++) {
if (s[i] != s[i - 1]) {
count++;
}
}
cout << count << endl;
return 0;
}
递归指函数直接或间接调用自己的过程。需注意终止条件以避免死循环。
int dg(int n) {
if (n == 87) {
return 1;
}
return dg(n + 1);
}
题目描述 计算两个整数的最大公约数。
代码实现
#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (a % b == 0) {
return b;
} else {
return gcd(b, a % b);
}
}
int main() {
int a, b;
cin >> a >> b;
cout << gcd(a, b) << endl;
return 0;
}
回溯法是一种试错过程,当发现当前路径不可行时回退到上一步选择其他分支。
#include <iostream>
using namespace std;
bool vis[10];
int plan[10];
int n;
void dfs(int step) {
if (step == n + 1) {
for (int i = 1; i <= n; i++) {
cout << plan[i] << " ";
}
cout << endl;
return;
}
for (int i = 1; i <= n; i++) {
if (vis[i]) continue;
plan[step] = i;
vis[i] = true;
dfs(step + 1);
vis[i] = false;
}
}
int main() {
cin >> n;
dfs(1);
return 0;
}
模拟竖式加法,逆序存储数组以方便处理进位。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
void s2BIG(string s, int a[]) {
a[0] = s.size();
for (int i = 1; i <= a[0]; i++) {
a[i] = s[a[0] - i] - '0';
}
}
void printBIG(int a[]) {
for (int i = a[0]; i >= 1; i--) {
cout << a[i];
}
cout << endl;
}
void addBIG(int a[], int b[], int c[]) {
c[0] = max(a[0], b[0]);
int u = 0;
for (int i = 1; i <= c[0]; i++) {
int t = a[i] + b[i] + u;
c[i] = t % 10;
u = t / 10;
}
if (u > 0) {
c[++c[0]] = u;
}
}
int a[1000005], b[100005], c[100005];
string sa, sb;
int main() {
cin >> sa >> sb;
s2BIG(sa, a);
s2BIG(sb, b);
addBIG(a, b, c);
printBIG(c);
return 0;
}
原理同加法,将进位改为退位,并需比较两数大小。
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
// ... (省略部分辅助函数,逻辑同上)
bool cmpBIG(int a[], int b[]) {
if (a[0] != b[0]) return a[0] < b[0];
for (int i = a[0]; i >= 1; i--)
if (a[i] != b[i]) return a[i] < b[i];
return false;
}
void subBIG(int a[], int b[], int c[]) {
c[0] = max(a[0], b[0]);
int u = 0;
for (int i = 1; i <= c[0]; i++) {
int t = a[i] - b[i] - u;
if (t < 0) {
c[i] = t + 10;
u = 1;
} else {
c[i] = t;
u = 0;
}
}
while (c[c[0]] == 0 && c[0] > 1) c[0]--;
}
int a[1005], b[1005], c[1005];
string sa, sb;
int main() {
cin >> sa >> sb;
s2BIG(sa, a);
s2BIG(sb, b);
if (cmpBIG(a, b)) subBIG(b, a, c);
else subBIG(a, b, c);
printBIG(c);
return 0;
}

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online
将 Markdown(GFM)转为 HTML 片段,浏览器内 marked 解析;与 HTML 转 Markdown 互为补充。 在线工具,Markdown 转 HTML在线工具,online
将 HTML 片段转为 GitHub Flavored Markdown,支持标题、列表、链接、代码块与表格等;浏览器内处理,可链接预填。 在线工具,HTML 转 Markdown在线工具,online
通过删除不必要的空白来缩小和压缩JSON。 在线工具,JSON 压缩在线工具,online