历年编程题
约 8103 字大约 27 分钟
2026-11-12
按当前对话提供的三套试题图片整理。第二套明确为2024年;第一套、第三套图片未显示年份,故标注“年份待确认”,不擅自推断。第一套第2题按“11~999回文数”理解;若原卷确为“三重回文数”等其他术语,请以原卷为准。
第一套(2023)
1. 数列分组求和
题目
计算 1 + 2*3 + 4*5*6 + ...,直到第 n 项。1、2*3、4*5*6 各为一项。
答案
#include <iostream>
using namespace std;
int main()
{
int n, num = 1;
long long sum = 0;
cin >> n;
for (int i = 1; i <= n; i++)
{
long long term = 1;
for (int j = 0; j < i; j++)
{
term *= num;
num++;
}
sum += term;
}
cout << sum << endl;
return 0;
}讲解
第 i 项由 i 个连续整数相乘。外层循环控制项数,内层循环控制本项乘几个数。term 是单项乘积,sum 是总和,num 始终指向下一个待乘的整数。
知识点
双重 for 循环、累加、累乘、数列规律、long long。
易错点
- 每一项开始要把
term重置为 1。 num不能在每一项开始时重置,否则每项都从 1 开始。- 大数可能溢出,
long long也有范围限制。
2. 寻找 11~999 的回文数
题目
寻找 11~999 范围内所有正读、倒读相同的回文数字。
答案
#include <iostream>
using namespace std;
int main()
{
for (int num = 11; num <= 999; num++)
{
int temp = num;
int rev = 0;
while (temp > 0)
{
rev = rev * 10 + temp % 10;
temp /= 10;
}
if (rev == num)
cout << num << " ";
}
return 0;
}讲解
temp % 10 取个位,temp / 10 去掉个位。每取出一位,就让反转数先乘 10 再加这一位。最后比较原数和反转数。
知识点
for、while、取模、整数除法、数字反转。
易错点
- 用
temp拆位,保留num原值用于比较。 - 反转公式是
rev = rev * 10 + digit。 - 若题目要求“三位回文数”,范围应改为 100~999;此处按图片中的 11~999 处理。
3. 设计 Tree 类
题目
设计 Tree 类,包含 ages(年龄)、type(类型);成员函数设置树类型、grow(int years) 使 ages 增加 years、age() 显示年龄。补充必要信息并写测试用例。
答案
#include <iostream>
#include <string>
using namespace std;
class Tree
{
private:
int ages;
string treeType;
public:
Tree(int a = 0, string t = "未知")
{
ages = a;
treeType = t;
}
void setType(string t)
{
treeType = t;
}
void grow(int years)
{
if (years > 0)
ages += years;
}
void age()
{
cout << "树龄:" << ages << endl;
}
void display()
{
cout << "类型:" << treeType << endl;
age();
}
};
int main()
{
Tree t(5, "松树");
t.display();
t.grow(3);
t.setType("柏树");
t.display();
return 0;
}讲解
把现实中的树抽象成类:属性放数据成员,行为放成员函数。构造函数负责初始化,grow() 修改年龄,age() 显示年龄。
知识点
class、private/public、构造函数、成员函数、对象创建与调用。
易错点
- 类定义结尾必须有分号。
- 构造函数没有返回值类型。
grow()是在原年龄上增加,不是覆盖。- C++ 同一作用域内不能让数据成员和成员函数同名。故用
treeType保存类型、setType()设置类型;若老师要求函数名type(),也应将数据成员改名。
4. MyPoint 友元函数 Offset
题目
MyPoint 有两个私有整型成员 m_x、m_y。友元函数原型为 MyPoint Offset(MyPoint &p, int offset),使两个成员同时增加 offset,写测试用例并显示结果。
答案
#include <iostream>
using namespace std;
class MyPoint
{
private:
int m_x, m_y;
public:
MyPoint(int x = 0, int y = 0)
{
m_x = x;
m_y = y;
}
void display()
{
cout << "(" << m_x << ", " << m_y << ")" << endl;
}
friend MyPoint Offset(MyPoint &p, int offset);
};
MyPoint Offset(MyPoint &p, int offset)
{
p.m_x += offset;
p.m_y += offset;
return p;
}
int main()
{
MyPoint p(2, 3);
p.display();
Offset(p, 5);
p.display();
return 0;
}讲解
友元函数不是类的成员函数,但经 friend 声明后可以访问私有成员。参数使用引用 MyPoint &p,因此函数内部修改的是原对象。
知识点
friend、引用参数、对象参数、对象返回值。
易错点
- 函数定义不写
MyPoint::Offset。 - 类内必须声明 friend。
- 传引用才能直接修改原对象。
- 返回类型是 MyPoint,函数末尾要
return p。
5. 判断 n 阶矩阵是否对称
题目
判断矩阵 A[n*n] 是否对称,n 小于 50;键盘输入 n 和矩阵元素,显示结果。
答案
#include <iostream>
using namespace std;
int main()
{
int n, a[50][50];
cin >> n;
if (n <= 0 || n >= 50)
{
cout << "阶数错误";
return 0;
}
for (int i = 0; i < n; i++)
for (int j = 0; j < n; j++)
cin >> a[i][j];
bool flag = true;
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (a[i][j] != a[j][i])
{
flag = false;
break;
}
}
if (!flag) break;
}
cout << (flag ? "是对称矩阵" : "不是对称矩阵");
return 0;
}讲解
对称矩阵满足 a[i][j] == a[j][i],即主对角线两侧对应元素相等。
知识点
二维数组、双重循环、bool 标志、break、矩阵转置。
易错点
- 必须是方阵。
- 比较
a[i][j]与a[j][i]。 - n<50,所以数组下标最大为49。
- 找到一组不相等元素即可提前退出。
6. Student 与 UStudent 继承
题目
父类 Student 含学号、姓名、成绩,有参构造函数和输出函数。子类 UStudent 公有继承 Student,新增专业,有参构造函数和输出函数。
答案
#include <iostream>
#include <string>
using namespace std;
class Student
{
protected:
int stu_no;
string name;
double score;
public:
Student(int no, string n, double s)
{
stu_no = no;
name = n;
score = s;
}
void display()
{
cout << stu_no << " " << name << " " << score << endl;
}
};
class UStudent : public Student
{
private:
string major;
public:
UStudent(int no, string n, double s, string m)
: Student(no, n, s)
{
major = m;
}
void display()
{
Student::display();
cout << "专业:" << major << endl;
}
};
int main()
{
UStudent s(1001, "张三", 90, "电子信息");
s.display();
return 0;
}讲解
子类继承父类共有信息,只新增自己的专业。初始化列表 : Student(no,n,s) 调用父类构造函数,Student::display() 复用父类输出。
知识点
公有继承、protected、构造函数初始化列表、作用域符号。
易错点
- 子类不能直接访问父类 private 成员,父类数据若需子类访问可设 protected。
- 父类先构造,子类后构造。
- 调用父类同名函数要写
Student::display()。
第二套 ( 2024 )
1. 用 while 显示 1~100 的质数
题目
用 while 语句显示 1~100 之间的质数。
答案
#include <iostream>
using namespace std;
int main()
{
int n = 2;
while (n <= 100)
{
bool prime = true;
int i = 2;
while (i * i <= n)
{
if (n % i == 0)
{
prime = false;
break;
}
i++;
}
if (prime) cout << n << " ";
n++;
}
return 0;
}讲解
质数大于1且只有1和自身两个因数。只需检查 2 到平方根之间是否有因数,代码用 i*i<=n 避免开方。
知识点
while、嵌套循环、取模、break、质数判断。
易错点
- 1不是质数,从2开始。
- 每个新数字都要重新设置
prime=true。 - 找到因数后设置 false 并 break。
2. 猜数字游戏
题目
定义一个 1~100 的整数,用户输入数字,比较大小并提示,直到猜对为止。
答案
#include <iostream>
using namespace std;
int main()
{
int answer = 56, guess;
while (true)
{
cout << "请输入1~100的数字:";
cin >> guess;
if (guess > answer)
cout << "猜大了" << endl;
else if (guess < answer)
cout << "猜小了" << endl;
else
{
cout << "猜对了" << endl;
break;
}
}
return 0;
}讲解
answer 在循环外保存正确答案,while(true) 不断接收输入,猜对时 break 结束。
知识点
while、条件判断、输入、break。
易错点
- 正确答案不要在循环内重新赋值。
- 猜对后必须 break。
- 若题目未要求随机数,直接赋固定值即可。
3. Desk 类
题目
设计 Desk 类,成员为单精度浮点数 length、width、height、weight。构造函数默认 height=1、weight=10;提供设置函数、显示函数、桌面面积函数。创建 d1(2,1)、d2(2.5,1.5,2,20),分别显示数据和面积。
答案
#include <iostream>
using namespace std;
class Desk
{
private:
float length, width, height, weight;
public:
Desk(float l, float w, float h = 1, float wt = 10)
{
length = l;
width = w;
height = h;
weight = wt;
}
void set(float l, float w, float h, float wt)
{
length = l;
width = w;
height = h;
weight = wt;
}
float area()
{
return length * width;
}
void display()
{
cout << length << " " << width << " "
<< height << " " << weight << endl;
cout << "面积:" << area() << endl;
}
};
int main()
{
Desk d1(2, 1);
Desk d2(2.5, 1.5, 2, 20);
d1.display();
d2.display();
return 0;
}讲解
d1 只传两个参数,后两个使用默认值;d2 传入四个参数。面积为 length×width。
知识点
类、构造函数、默认参数、成员函数、返回值。
易错点
- 默认参数从右向左连续设置。
area()要返回结果。set()是修改已有对象,不是构造函数。
4. sinFun 泰勒展开
题目
编写 sinFun() 求 sin(x) 近似值,以后续项绝对值小于 10−8 为结束条件;调用该函数求 sin(x)+sin(x+1)+...+sin(x+5) 并输出。
公式:
sinx=x−3!x3+5!x5−⋯
答案
#include <iostream>
#include <cmath>
using namespace std;
double sinFun(double x)
{
double sum = 0;
double term = x;
int k = 0;
while (fabs(term) >= 1e-8)
{
sum += term;
k++;
term = -term * x * x / ((2 * k) * (2 * k + 1));
}
return sum;
}
int main()
{
double x, result = 0;
cin >> x;
for (int i = 0; i <= 5; i++)
result += sinFun(x + i);
cout << result << endl;
return 0;
}讲解
首项是 x。相邻项关系:
tk=−tk−1(2k)(2k+1)x2
每次累加当前项,再计算下一项;当前项绝对值小于精度要求时结束。
知识点
函数、泰勒展开、级数累加、递推、fabs、精度控制。
易错点
- 不要用库函数 sin() 替代题目要求的泰勒算法。
- C++ 的 sin() 参数是弧度。
sum是累计和,term是当前项。- 分母为
(2*k)*(2*k+1),括号不能漏。 - x 很大时泰勒展开会有数值误差,考试按给定范围处理。
✅ C++ / C 里面科学计数法写法规则
格式:小数E指数 或者 小数e指数,大小写 e 都可以 含义:a×10b
注意:e 前面必须有数字,e后面必须是整数,不能写 10e-3!
例子对照表
| 代码写法 | 数学式子 | 十进制小数 |
|---|---|---|
1e0 | 1×100 | 1.0 |
1e1 | 1×101 | 10.0 |
1e2 | 1×102 | 100.0 |
1e-2 | 1×10−2 | 0.01 |
1e-6 | 1×10−6 | 0.000001 |
1e-8 | 1×10−8 | 0.00000001(你代码里这个) |
2.5e-3 | 2.5×10−3 | 0.0025 |
6.02e23 | 6.02×1023 | 阿伏伽德罗常数 |
等价写法
1e-8 和 1E-8 完全一样,e 不分大小写。
❌ 常见错误(考试、写数值代码很容易错)
10e-8❌ 10×10−8=1×10−7,不是 10−8 想要 10−8 只能写1e-8e-5❌,e前面不能空,必须写数字:1e-51e-2.5❌,e后面只能是整数
5. Student 静态成员统计
题目
Student 有 name、stu_no、score。定义静态成员 count、sum、ave,分别统计对象总数、总分、平均分,并用静态成员函数 show() 显示。
答案
#include <iostream>
#include <string>
using namespace std;
class Student
{
private:
string name;
int stu_no;
double score;
static int count;
static double sum;
static double ave;
public:
Student(string n, int no, double s)
{
name = n;
stu_no = no;
score = s;
count++;
sum += score;
ave = sum / count;
}
static void show()
{
cout << "人数:" << count << endl;
cout << "总分:" << sum << endl;
cout << "平均分:" << ave << endl;
}
};
int Student::count = 0;
double Student::sum = 0;
double Student::ave = 0;
int main()
{
Student s1("张三", 1001, 90);
Student s2("李四", 1002, 80);
Student s3("王五", 1003, 70);
Student::show();
return 0;
}讲解
普通成员属于每个对象;静态成员属于整个类,所有对象共享。每创建一个对象,构造函数就更新 count 和 sum,再计算 ave。
知识点
static 数据成员、静态成员函数、类外初始化、构造函数。
易错点
- 静态成员必须在类外定义和初始化。
- 静态成员函数没有 this 指针,不能直接访问某个对象的普通成员。
- 若 count 可能为0,计算平均值前要判断。
6. Fraction 分数类与运算符重载
题目
设计分数类,分子分母均为整数,支持 +、-、*、/,计算结果化为最简形式。
答案
#include <iostream>
#include <cstdlib>
using namespace std;
int gcd(int a, int b)
{
a = abs(a);
b = abs(b);
while (b != 0)
{
int t = a % b;
a = b;
b = t;
}
return a;
}
class Fraction
{
private:
int num, den;
void simplify()
{
if (den < 0)
{
den = -den;
num = -num;
}
int g = gcd(num, den);
if (g != 0)
{
num /= g;
den /= g;
}
}
public:
Fraction(int n = 0, int d = 1)
{
num = n;
den = d;
if (den == 0) den = 1; // 实际应用应报告错误
simplify();
}
Fraction operator+(const Fraction &f) const
{
return Fraction(num * f.den + f.num * den,
den * f.den);
}
Fraction operator-(const Fraction &f) const
{
return Fraction(num * f.den - f.num * den,
den * f.den);
}
Fraction operator*(const Fraction &f) const
{
return Fraction(num * f.num, den * f.den);
}
Fraction operator/(const Fraction &f) const
{
return Fraction(num * f.den, den * f.num);
}
void display() const
{
cout << num << "/" << den << endl;
}
};
int main()
{
Fraction a(1, 2), b(1, 3);
(a + b).display();
(a - b).display();
(a * b).display();
(a / b).display();
return 0;
}讲解
加减法先通分,乘法分子分母分别相乘,除法乘以倒数。构造函数中调用 simplify(),使每次运算产生的结果自动约分。
知识点
运算符重载、operator+/-/*//、最大公约数、辗转相除法、构造函数。
易错点
- 加减法不能直接分子分母分别相加减。
- 除法要检查除数分子不为0。
- 分母不能为0;上面为手写框架做了简单兜底,严谨程序应明确报错。
- 负号建议统一放在分子,分母保持正数。
- 返回新对象后通过构造函数约分。
Fraction 分数类与运算符重载(注释版)
#include <iostream>
#include <cmath> // abs() 整数绝对值函数头文件
using namespace std;
class Fraction
{
private:
int num; // 分子
int den; // 分母
// 辗转相除法求最大公约数
int gcd(int a,int b){
a=fabs(a); b=fabs(b); // 先转成正数,不影响最大公约数
while(b){ // b不等于0继续循环
int t=a%b; // 取余数
a=b; // a更新为b
b=t; // b更新为余数
}
return a; // b=0时,a就是最大公约数
}
// 约分函数:化为最简分数,统一符号
void reduce(){
int g = gcd(num,den);
num /= g;
den /= g;
// 规定负号放在分子,分母永远为正数
if(den < 0){
num = -num;
den = -den;
}
}
public:
// 构造函数:默认 0/1,创建时自动约分
Fraction(int n=0,int d=1):num(n),den(d){
reduce();
}
// 重载 + 运算符
Fraction operator+(const Fraction &o)const{
// 公式 n1/d1 + n2/d2 = (n1*d2 + n2*d1) / (d1*d2)
return Fraction(num*o.den + o.num*den, den*o.den);
}
// 重载 - 运算符
Fraction operator-(const Fraction &o)const{
// 公式 n1/d1 - n2/d2 = (n1*d2 - n2*d1) / (d1*d2)
return Fraction(num*o.den - o.num*den, den*o.den);
}
// 重载 * 运算符
Fraction operator*(const Fraction &o)const{
// 公式 n1/d1 * n2/d2 = (n1*n2) / (d1*d2)
return Fraction(num*o.num, den*o.den);
}
// 重载 / 运算符
Fraction operator/(const Fraction &o)const{
// 公式 n1/d1 ÷ n2/d2 = (n1*d2) / (d1*n2) 除以一个分数等于乘倒数
return Fraction(num*o.den, den*o.num);
}
// 重载输出流 <<,用来打印分数
friend ostream& operator<<(ostream &os,const Fraction &f){
if(f.den == 1) // 如果分母是1,直接输出整数
os << f.num;
else // 否则输出 分子/分母
os << f.num << "/" << f.den;
return os;
}
};
int main(){
Fraction a(1,2),b(1,3);
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "a + b = " << a+b << endl;
cout << "a - b = " << a-b << endl;
cout << "a * b = " << a*b << endl;
cout << "a / b = " << a/b << endl;
return 0;
}运行输出:
a = 1/2
b = 1/3
a + b = 5/6
a - b = 1/6
a * b = 1/6
a / b = 3/2辗转相除法(欧几里得算法)原理
一句话核心:
两个数的最大公约数 = 较小数 和 「大数 ÷ 小数的余数」的最大公约数 直到余数等于0,此时那个非0的数就是最大公约数。
举个例子:求 gcd(18,12)
- 18mod12=6 → gcd(18,12)=gcd(12,6)
- 12mod6=0 → gcd(12,6)=gcd(6,0)
- 余数是0,停止,6就是最大公约数
为什么这个是对的?(通俗理解)
设 a=b×k+r,也就是:
a÷b=k⋯r
- 如果一个数能同时整除 a 和 b,那它一定也能整除余数 r
- 反过来:能同时整除 b 和 r 的数,也一定能整除 a 👉 所以:(a,b) 的公因数集合 和 (b,r) 的公因数集合完全一样,最大公约数自然相等。
简单大白话: 大数减去若干个小数之后剩下的余数,不改变它们共有的最大因子。
对应代码对照
int gcd(int a,int b){
a=abs(a); b=abs(b);
while(b != 0){ // 余数b不为0,继续循环
int t = a % b; // 算出余数r
a = b; // 小数变成新的a
b = t; // 余数变成新的b
}
return a; // b=0时,a就是gcd
}循环就是反复做:gcd((a,b)) → gcd(b,a%b)
考场极简背诵版
公式:gcd((a,b))=gcd(b,a%b) 终止条件:余数为0,返回另一个数。
补充
- 只关心公因数,正负不影响,所以代码开头先取
abs() - 这是求gcd最快的算法,比从大到小暴力试除高效很多
从大到小暴力试除(实在不会就写这个)
int gcd(int a, int b)
{
a = fabs(a);
b = fabs(b);
// 取较小的值作为起点,往下试
int min_val = (a < b) ? a : b;
for(int i = min_val; i >= 1; i--)
{
// i 能同时整除 a 和 b
if(a % i == 0 && b % i == 0)
{
return i;
}
}
return 1; // 最差情况,公约数是1
}第三套(2025)
1. 成绩等级判断
题目
输入考试分数(0~100),90~100为A,60~89为B,0~59为C。
答案
#include <iostream>
using namespace std;
int main()
{
int score;
cin >> score;
if (score < 0 || score > 100)
cout << "输入错误";
else if (score >= 90)
cout << "A";
else if (score >= 60)
cout << "B";
else
cout << "C";
return 0;
}讲解
先排除非法范围,再从高分段向低分段判断。
知识点
if、else if、多分支、范围判断。
易错点
- 90属于A,60属于B。
- 先判断非法范围。
- 条件顺序从高到低更直观。
2. 递归 power(x,y)
题目
递归函数 power(int x,int y) 计算 x 的 y 次幂,y 为正整数,在主函数输入并输出。
答案
#include <iostream>
using namespace std;
int power(int x, int y)
{
if (y == 0)
return 1;
return x * power(x, y - 1);
}
int main()
{
int x, y;
cin >> x >> y;
cout << power(x, y);
return 0;
}讲解
递归关系为 x^y = x * x^(y-1),终止条件为 x^0=1。
知识点
递归、函数返回值、终止条件。
易错点
- 必须有终止条件。
- 每次 y 要减小。
- y=0 时结果为1。
- int 可能溢出,按题目数据范围考虑。
3. Stock 类
题目
Stock 包含 code、name、price;code 和 name 为 string,price 为 double。构造函数默认 price=1.0;提供 set()、display()。创建 st_a(688001、中国银行、48)和 st_b(688001、******,价格使用默认值)并输出。
答案
#include <iostream>
#include <string>
using namespace std;
class Stock
{
private:
string code, name;
double price;
public:
Stock(string c, string n, double p = 1.0)
{
code = c;
name = n;
price = p;
}
void set(string c, string n, double p)
{
code = c;
name = n;
price = p;
}
void display()
{
cout << code << " " << name << " " << price << endl;
}
};
int main()
{
Stock st_a("688001", "中国银行", 48);
Stock st_b("688001", "******");
st_a.display();
st_b.display();
return 0;
}讲解
p=1.0 是默认参数。传入第三个参数时使用实参,省略时使用1.0。
知识点
类、string、double、构造函数默认参数、set、display。
易错点
- price 是 double。
- 默认参数放在参数列表右侧。
- 默认参数只需在声明/定义处设置一次。
4. X、Y1、Y2 友元综合
题目
X 有私有成员 i。Y1 的成员函数 g(X*) 是 X 的友元成员函数,使 i 加1;Y2 是 X 的友元类,其 f(X*) 使 i 加5;普通函数 h(X*) 是 X 的友元函数,使 i 加10。创建 x、y1、y2 并依次调用。
答案
#include <iostream>
using namespace std;
class X;
class Y1
{
public:
void g(X *p);
};
class Y2
{
public:
void f(X *p);
};
class X
{
private:
int i;
public:
X(int a = 0) { i = a; }
void show()
{
cout << "i=" << i << endl;
}
friend void Y1::g(X *p);
friend class Y2;
friend void h(X *p);
};
void Y1::g(X *p) { p->i += 1; }
void Y2::f(X *p) { p->i += 5; }
void h(X *p) { p->i += 10; }
int main()
{
X x(0);
Y1 y1;
Y2 y2;
y1.g(&x);
x.show();
y2.f(&x);
x.show();
h(&x);
x.show();
return 0;
}讲解
初始 i=0,依次加1、加5、加10,最终 i=16。X* 是对象指针,p->i 访问对象成员。
知识点
友元成员函数、友元类、普通友元函数、前向声明、指针。
易错点
friend void Y1::g(X *p)只授权 Y1 的 g,不是整个 Y1。friend class Y2授权整个 Y2 类。h(&x)传对象地址。- 指针访问成员用
->。 - 定义友元成员函数时,X 必须已经完整定义。
5. 牛顿迭代法求平方根
题目
用公式:
xn+1=21(xn+xna)
求平方根,前后两次 x 的绝对差小于 10−8 时结束。输入非负实数 a 和正整数 num,求 sqrt(a) 到 sqrt(a+num+1)。
答案
#include <iostream>
#include <cmath>
using namespace std;
double mySqrt(double a)
{
if (a == 0) return 0;
double x = a;
double next;
do
{
next = 0.5 * (x + a / x);
if (fabs(next - x) < 1e-8)
return next;
x = next;
} while (true);
}
int main()
{
double a;
int num;
cin >> a >> num;
if (a < 0 || num <= 0)
{
cout << "输入错误";
return 0;
}
for (int i = 0; i <= num + 1; i++)
cout << mySqrt(a + i) << endl;
return 0;
}讲解
x 是当前近似值,next 是新近似值。每次按牛顿公式更新,比较两次结果的绝对误差。主循环 i 从0到num+1,共 num+2 个结果。
知识点
数值迭代、do while、fabs、精度控制、函数封装。
易错点
- a=0 要单独处理,避免除以0。
- 误差写
fabs(next-x)。 - 循环终点是
num+1,不是num。 - 题目输入是非负实数,负数要处理。
6. Employee 与 Manager 继承
题目
Employee 数据成员:工号、姓名、性别、部门、工资;有无参和有参构造函数、输出函数。Manager 公有继承 Employee,增加职称,有无参和有参构造函数、输出函数。主函数分别创建父类、子类对象并输出;工资保留两位小数。
答案
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
class Employee
{
protected:
int id;
string name, gender, department;
double salary;
public:
Employee()
{
id = 0;
name = gender = department = "";
salary = 0;
}
Employee(int i, string n, string g, string d, double s)
{
id = i;
name = n;
gender = g;
department = d;
salary = s;
}
void display()
{
cout << id << " " << name << " "
<< gender << " " << department << " "
<< fixed << setprecision(2) << salary << endl;
}
};
class Manager : public Employee
{
private:
string title;
public:
Manager() : Employee()
{
title = "";
}
Manager(int i, string n, string g, string d,
double s, string t)
: Employee(i, n, g, d, s)
{
title = t;
}
void display()
{
Employee::display();
cout << "职称:" << title << endl;
}
};
int main()
{
Employee e(1001, "张三", "男", "技术部", 8000.5);
Manager m(1002, "李四", "女", "管理部", 12000.5, "经理");
e.display();
m.display();
return 0;
}讲解
Employee 保存共有属性,Manager 只增加 title。子类初始化列表调用父类构造函数,输出时调用 Employee::display() 复用父类逻辑。
知识点
继承、protected、初始化列表、父类成员函数调用、iomanip。
易错点
- 父类成员要让子类访问时不能是 private。
- 子类构造函数通过
: Employee(...)初始化父类部分。 fixed << setprecision(2)才是小数点后两位。- 父类构造先于子类构造执行。
7. 6174 黑洞数与文件操作
题目
输入四位正整数,各位数字不能完全相同;否则输出“输入有错”。将数字各位从大到小排列得到降序数,再颠倒得到升序数,求降序数减升序数,重复直到6174。将每一步结果写入 Blackhole.txt。文件流为类的数据成员,构造函数打开文件,析构函数关闭文件。
答案
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class Blackhole
{
private:
fstream file;
public:
Blackhole()
{
file.open("Blackhole.txt", ios::out | ios::trunc);
if (!file.is_open())
cout << "文件打开失败" << endl;
}
void run(int num)
{
if (num < 1000 || num > 9999)
{
cout << "输入有错" << endl;
return;
}
int a = num / 1000;
int b = num / 100 % 10;
int c = num / 10 % 10;
int d = num % 10;
if (a == b && b == c && c == d)
{
cout << "输入有错" << endl;
return;
}
while (true)
{
int arr[4] = {
num / 1000,
num / 100 % 10,
num / 10 % 10,
num % 10
};
// 冒泡排序:小到大
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3 - i; j++)
{
if (arr[j] > arr[j + 1])
{
int t = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = t;
}
}
}
int small = arr[0] * 1000 + arr[1] * 100
+ arr[2] * 10 + arr[3];
int big = arr[3] * 1000 + arr[2] * 100
+ arr[1] * 10 + arr[0];
num = big - small;
cout << setw(4) << setfill('0') << big
<< " - "
<< setw(4) << setfill('0') << small
<< " = "
<< setw(4) << setfill('0') << num
<< endl;
if (file.is_open())
{
file << setw(4) << setfill('0') << big
<< " - "
<< setw(4) << setfill('0') << small
<< " = "
<< setw(4) << setfill('0') << num
<< endl;
}
if (num == 6174)
break;
}
}
~Blackhole()
{
if (file.is_open())
file.close();
}
};
int main()
{
int num;
cin >> num;
Blackhole b;
b.run(num);
return 0;
}讲解
- 拆位:千位
num/1000,百位num/100%10,十位num/10%10,个位num%10。 - 冒泡排序将四位数字从小到大排列。
small按小到大组合,big按大到小组合。- 每轮执行
big-small,直到结果为6174。 - 构造函数打开文件,
file <<写入,析构函数关闭文件。
知识点
数字拆分、数组、冒泡排序、while、类、构造/析构函数、fstream、文件写入、格式化输出。
易错点
- 必须检查四位数和四位数字是否全相同。
- 降序数减升序数,不能反过来。
0378作为整数会存成378;下一轮拆位仍可还原0、3、7、8。显示前导0要用setw(4)和setfill('0')。- 文件对象应是类成员。
- 构造函数打开文件,析构函数关闭文件。
ios::trunc会清空旧文件;若要追加,使用ios::app。- 对6174本身也要执行一次计算,因此先计算、后判断。
6174黑洞数 C++ 全总结(考场专用)
题目要求回顾
- 输入4位正整数;四位数字全部相同,输出
输入有错- 求:降序数 − 升序数,反复迭代,直到结果等于6174
fstream文件流作为类的私有成员- 构造函数打开文件,析构函数关闭文件
- 每一步控制台输出,同时写入
Blackhole.txt- 4位数字,不足4位要补前导0
头文件清单
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm> // sort、reverse、greater 都在这里
using namespace std;核心知识点汇总
1. sort 相关(重点)
sort(起始迭代器, 结束迭代器, 比较规则),区间 [begin, end),左闭右开
s.begin():指向第一个字符s.end():指向最后一个字符后面(不包含)>
❌ 错误:
sort(s),sort必须传起止位置
| 写法 | 说明 |
|---|---|
sort(s.begin(), s.end()) | 默认升序(从小到大,a < b) |
sort(s.rbegin(), s.rend()) | 反向迭代器,直接降序 |
sort(s.begin(), s.end(), greater<char>()) | 库自带比较器,降序 |
手写全局cmp函数 sort(s.begin(), s.end(), cmp) | 自定义降序 |
| sort升序 + reverse反转 | 先排升序,反转得到降序 |
reverse 也是全局算法:
reverse(s.begin(), s.end())❌ 没有s.reverse()这种成员函数!
2. cmp函数位置(高频坑)
bool cmp(char a,char b) 是全局函数 ✅ 写在 #include 之后、类定义之前(最稳,不会未定义) ✅ 也可以写在类结束后、main之前 ❌ 不能写在别的函数里面、不能直接作为类成员传给sort
bool cmp(char a, char b)
{
return a > b; // 返回true:a排在左边,大的在前=降序
}3. string 字符比较原理
'0'~'9' 的ASCII码大小顺序和数字大小一致,直接比较字符即可。 '9' > '8' > ... > '0'
4. 两个辅助转换函数(备用)
// 数字转4位字符串,自动补前导0
string int2str(int x)
{
string s = to_string(x);
while(s.size() < 4)
s = "0" + s;
return s;
}
// 4位字符串转整数(替代stoi,老编译器兜底)
int str2int(string s)
{
return (s[0]-'0')*1000 + (s[1]-'0')*100 + (s[2]-'0')*10 + (s[3]-'0');
}
'5' - '0':字符转数字,利用ASCII差值
版本合集
版本1|首选背诵版 · sort + greater<char>(推荐⭐⭐⭐⭐⭐)
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
class Blackhole {
private:
fstream file;
public:
Blackhole()
{
file.open("Blackhole.txt", ios::out | ios::trunc);
}
string int2str(int x)
{
string s = to_string(x);
while(s.size() < 4)
s = "0" + s;
return s;
}
void run(int num)
{
if(num < 1000 || num > 9999)
{
cout << "输入有错" << endl;
return;
}
string s = int2str(num);
if(s[0]==s[1] && s[1]==s[2] && s[2]==s[3])
{
cout << "输入有错" << endl;
return;
}
while (true)
{
string s_small = s;
sort(s_small.begin(), s_small.end());
string s_big = s;
sort(s_big.begin(), s_big.end(), greater<char>());
int small = stoi(s_small);
int big = stoi(s_big);
int res = big - small;
cout << s_big << " - " << s_small << " = " << int2str(res) << endl;
file << s_big << " - " << s_small << " = " << int2str(res) << endl;
if(res == 6174) break;
s = int2str(res);
}
}
~Blackhole()
{
if(file.is_open())
file.close();
}
};
int main()
{
int n;
cin >> n;
Blackhole bh;
bh.run(n);
return 0;
}版本2|sort + reverse 版(不用rbegin/rend,好理解)
只替换while循环部分:
while (true)
{
string s_small = s;
sort(s_small.begin(), s_small.end());
string s_big = s_small;
reverse(s_big.begin(), s_big.end());
int small = stoi(s_small);
int big = stoi(s_big);
int res = big - small;
cout << s_big << " - " << s_small << " = " << int2str(res) << endl;
file << s_big << " - " << s_small << " = " << int2str(res) << endl;
if(res == 6174) break;
s = int2str(res);
}版本3|手写cmp全局函数版
#include <iostream>
#include <fstream>
#include <string>
#include <algorithm>
using namespace std;
bool cmp(char a, char b)
{
return a > b;
}
class Blackhole {
private:
fstream file;
public:
Blackhole()
{
file.open("Blackhole.txt", ios::out | ios::trunc);
}
string int2str(int x)
{
string s = to_string(x);
while(s.size() < 4)
s = "0" + s;
return s;
}
void run(int num)
{
if(num < 1000 || num > 9999)
{
cout << "输入有错" << endl;
return;
}
string s = int2str(num);
if(s[0]==s[1] && s[1]==s[2] && s[2]==s[3])
{
cout << "输入有错" << endl;
return;
}
while (true)
{
string s_small = s;
sort(s_small.begin(), s_small.end());
string s_big = s;
sort(s_big.begin(), s_big.end(), cmp);
int small = stoi(s_small);
int big = stoi(s_big);
int res = big - small;
cout << s_big << " - " << s_small << " = " << int2str(res) << endl;
file << s_big << " - " << s_small << " = " << int2str(res) << endl;
if(res == 6174) break;
s = int2str(res);
}
}
~Blackhole()
{
if(file.is_open())
file.close();
}
};
int main()
{
int n;
cin >> n;
Blackhole bh;
bh.run(n);
return 0;
}版本4|无sort,手写冒泡(兜底,不让用algorithm时)
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class Blackhole {
private:
fstream file;
public:
Blackhole()
{
file.open("Blackhole.txt", ios::out | ios::trunc);
}
string int2str(int x)
{
string s = to_string(x);
while(s.size() < 4)
s = "0" + s;
return s;
}
int str2int(string s)
{
return (s[0]-'0')*1000 + (s[1]-'0')*100 + (s[2]-'0')*10 + (s[3]-'0');
}
void bubble_asc(string &s)
{
char t;
for(int i=0;i<3;i++)
for(int j=0;j<3-i;j++)
{
if(s[j]>s[j+1])
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
void bubble_desc(string &s)
{
char t;
for(int i=0;i<3;i++)
for(int j=0;j<3-i;j++)
{
if(s[j]<s[j+1])
{
t=s[j];
s[j]=s[j+1];
s[j+1]=t;
}
}
}
void run(int num)
{
if(num < 1000 || num > 9999)
{
cout << "输入有错" << endl;
return;
}
string s = int2str(num);
if(s[0]==s[1] && s[1]==s[2] && s[2]==s[3])
{
cout << "输入有错" << endl;
return;
}
while (true)
{
string s_small = s;
bubble_asc(s_small);
string s_big = s;
bubble_desc(s_big);
int small = str2int(s_small);
int big = str2int(s_big);
int res = big - small;
cout << s_big << " - " << s_small << " = " << int2str(res) << endl;
file << s_big << " - " << s_small << " = " << int2str(res) << endl;
if(res == 6174) break;
s = int2str(res);
}
}
~Blackhole()
{
if(file.is_open())
file.close();
}
};
int main()
{
int n;
cin >> n;
Blackhole bh;
bh.run(n);
return 0;
}版本5|终极兼容版(无stoi、无to_string,纯基础语法)
把 int2str、str2int 全部手写,适合非常老旧编译器:
string int2str(int x)
{
string s;
s += (char)('0' + x/1000);
s += (char)('0' + x/100%10);
s += (char)('0' + x/10%10);
s += (char)('0' + x%10);
return s;
}
int str2int(string s)
{
return (s[0]-'0')*1000 + (s[1]-'0')*100 + (s[2]-'0')*10 + (s[3]-'0');
}版本对比速查表
| 版本 | 依赖 | 优点 | 缺点 | 推荐度 |
|---|---|---|---|---|
| sort+greater | C++11,algorithm | 代码短、好写 | 极少数老编译器不支持C++11 | ⭐⭐⭐⭐⭐首选 |
| sort+reverse | C++11,algorithm | 逻辑直白,不用记greater | 多一行reverse | ⭐⭐⭐⭐ |
| 手写cmp | C++11,algorithm | 理解比较原理 | 多写一个全局函数 | ⭐⭐⭐⭐ |
| 冒泡排序 | 无algorithm | 不依赖sort | 代码长,循环容易写错 | ⭐⭐⭐兜底 |
| 终极兼容 | 无C++11函数 | 全部编译器可跑 | 转换函数多,代码量大 | ⭐⭐⭐应急 |
📝 背诵流程口诀
- 写类,私有成员放
fstream file - 构造函数打开文件,析构函数关闭文件
- 写
int2str补前导0 - 两层校验:不是4位 / 四位全相同 → 输入有错
- while循环:复制字符串,分别得到升序、降序
- 大数减小数,输出+写文件
- 结果等于6174退出;否则更新字符串继续循环
⚠️ 考场高频坑汇总
fstream必须是类的成员,不能写在run里面!- 循环末尾
s = int2str(res)极易忘记,忘记直接死循环 sort、reverse是全局函数,不能 s.sort() / s.reverse()- cmp不能写在函数内部,不能直接当成员函数传给sort
- 输出一定要4位,前导0不能丢,交给int2str处理
- 循环逻辑:先计算,再判断是否等于6174
总复习:核心知识点索引
| 模块 | 对应大题 | 必须掌握 |
|---|---|---|
| 循环与累加 | 第一套1、2024质数/猜数 | for、while、累加/累乘、break |
| 数字处理 | 第一套2、第三套6174 | %10、/10、反转、拆位 |
| 数组与排序 | 第一套矩阵、第三套6174 | 二维数组、冒泡排序 |
| 普通函数与递归 | 2024 sinFun、第三套 power | 参数、返回值、递归终止 |
| 数学计算 | 2024 sinFun、第三套平方根 | 泰勒项递推、牛顿迭代、fabs |
| 类与对象 | Tree、Desk、Stock | 数据成员、构造函数、set/display |
| 友元 | MyPoint、X/Y1/Y2 | 普通友元、友元成员、友元类 |
| 继承 | Student/UStudent、Employee/Manager | public、protected、初始化列表 |
| static | 2024 Student | 类外初始化、共享数据 |
| 运算符重载 | 2024 Fraction | operator、约分、最大公约数 |
| 文件操作 | 第三套6174 | open、写入、close、析构函数 |
考场解题顺序
- 圈出题目动词:输入、判断、计算、显示、设置、统计、继承、写文件。
- 判断题目结构:循环、函数、类、友元、继承、static、运算符重载、文件。
- 列出输入变量、数据成员、中间变量和输出结果。
- 先写框架,再填公式和逻辑。
- 检查边界、初始值、循环终止条件、返回值、访问权限和文件关闭。
复习目标:不是背住每一道原题,而是看到题目就能识别它对应的 C++ 结构,再把题目条件填入模板。
