作者:王昊成(小红书:秋来拾光),无所不能哈基咪
本文由同学分享个人经验,仅供学习交流,严禁倒卖。 具体要求请以学校及学院最新发布的信息为准。
经典上机习题
经典上机习题
斐波那契数列
eg:设计程序输出Fibonacci数列的前20项, 要求每行输出5个数据
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
int fib0=0,fib1=1,fib2;
cout<<setw(5)<<fib0<<setw(5)<<fib1;
//先输出前两个
for(int n=3;n<=20;n++){
fib2=fib0+fib1;
cout<<setw(5)<<fib2;
//循环并输出17个
if(n%5==0)
cout<<endl;//控制每行5个数据换行
fib0=fib1;
fib1=fib2;
}
return 0;
}
输入一个整数n,求出Fibonacci数列中不大于n的最大的一个数,其中Fibonacci数列的定义为F (0) =0;F (n)=F (n-1) +F (n-2)
输入一个整数n
输出Fibonacci数列中不大于n的最大的一个数
样例输入5000
样例输出4181
#include<iostream>
using namespace std;
int main() {
int a = 0, b = 1,n;
cin >> n;
if (n <= 0) { cout << 0; }
else {
for (b; b < n;) {
int res = a;
a = b;
b = b + res;
}
cout << a;
}
}
十进制转二进制
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
int main() {
int n;
cin >> n;
if (n > 0) {
vector <int>vec;
while (n > 0) {
vec.push_back(n % 2);
n /= 2;
}
for (int i = vec.size()-1; i >=0 ; i--) {
cout << vec[i];
}
return 0;
}//n是正数
else if (n == 0) {
cout << 0 << endl;
return 0;
}
else { //转三十二位二进制
n = -n;//取绝对值
vector <int>vec;
while (n > 0) {
vec.push_back(n % 2);
n /= 2;
}//取余
int size = vec.size();
for (int i = 0; i < 32 -size; i++) {
vec.push_back(0);
}//补齐32位
vector<int> res(vec.size());
for (int i = 31; i >= 0; i--) {
res[i] = vec[31 - i];
}//正序
for (int i = 0; i < 32; i++) {
if (res[i] == 0) { res[i] = 1; }
else if (res[i] == 1)
{
res[i] = 0;
}
}//反码
for (int i = 31; i >=0; i--) {
res[i] += 1;
if (res[i] == 2) {
res[i] = 0;
}
else { break; }
}//加一
for (int i = 0; i < 32; i++) { cout << res[i]; }
//输出
}
}
质因式分解
求出a!b!的质因数分解,其中n!=123…n。
输入
输入两个整数a, b(2≤a, b≤100)。
输出
输出a!b!的质因数分解,形如a1a2a3*…(a1≤a2≤a3≤…)。
样例输入
3 10
样例输出
222222222333355*7
提示
注意星号用英文字符!
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//判断是否是素数
bool isprime(int n) {
if (n < 2) { return false; }
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int a, b;
cin >> a >> b;
vector<int>prime;
vector<int>res;
for (int i = 2; i <= 100; i++) {
if (isprime(i)) { prime.push_back(i); }
}
//提取0到100的全部素数
for (int i = 0; i < prime.size(); i++) {
int te = a;
int time = 0;
while (te >= prime[i]) {
int temp = te / prime[i];
te /= prime[i];
time += temp;
}
for (int j = 1; j <= time; j++) {
res.push_back(prime[i]);
}
} //分解储存a
for (int i = 0; i < prime.size(); i++) {
int te = b;
int time = 0;
while (te >= prime[i]) {
int temp = te/ prime[i];
te /= prime[i];
time += temp;
}
for (int j = 1; j <= time; j++) {
res.push_back(prime[i]);
}
}
//分解储存b
sort(res.begin(), res.end());//排序
for (int i = 0; i < res.size(); i++) {
if (i == 0) { cout << res[i]; }
else { cout << "*" << res[i]; }
}//输出
}
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
// 分解单个数字x的质因数,返回展开的质因数列表
vector<int> factorize(int x) {
vector<int> factors;
if (x < 2) return factors; // 1没有质因数
for (int i = 2; i <= x; ++i) {
while (x % i == 0) { // 反复除以i,直到不能整除
factors.push_back(i);
x /= i;
}
}
return factors;
}
// 获取n!的质因数展开列表
vector<int> factorialFactors(int n) {
vector<int> res;
for (int i = 2; i <= n; ++i) { // 1的质因数为空,从2开始
vector<int> temp = factorize(i);
res.insert(res.end(), temp.begin(), temp.end());
}
return res;
}
int main() {
int a, b;
cin >> a >> b;
// 获取a!和b!的质因数列表
vector<int> factorsA = factorialFactors(a);
vector<int> factorsB = factorialFactors(b);
// 合并两个列表
vector<int> totalFactors = factorsA;
totalFactors.insert(totalFactors.end(), factorsB.begin(), factorsB.end());
// 排序(保证质因数从小到大)
sort(totalFactors.begin(), totalFactors.end());
// 按格式输出
for (int i = 0; i < totalFactors.size(); ++i) {
if (i > 0) {
cout << "*";
}
cout << totalFactors[i];
}
cout << endl;
return 0;
}
#include <iostream>
using namespace std;
int main() {
long long n;
cin >> n;
bool first = true;
int count = 0;
for (long long i = 2; i * i <= n; i++) {
count = 0;
while (n % i == 0) {
count++;
n = n / i;
}
if (count > 0) {
if (!first) {
cout << " * ";
}
first = false;
if (count == 1) {
cout << i;
} else {
cout << i << "^" << count;
}
}
}
if (n > 1) {
if (!first) {
cout << " * ";
}
cout << n;
}
cout << endl;
return 0;
}
vector<int> factorize(int x): 是 C++ 中的函数声明,用于定义一个名为 factorize 的函数
各部分含义
vector<int>:函数的返回值类型,表示该函数执行后会返回一个存储int类型元素的vector容器(可理解为 “整数列表”)。这里的vector是 C++ 标准库中的动态数组容器,<int>指定容器中元素的类型为整数。
factorize:函数的名称,调用函数时通过这个名称标识。
(int x):函数的参数列表,表示调用该函数时需要传入一个int类型的参数,参数名为x(通常用于接收需要分解质因数的整数)。
结合功能理解
结合之前的代码逻辑,这个函数声明的完整含义是:定义一个名为factorize的函数,接收一个整数x作为输入,返回一个存储x的所有质因数的整数列表(vector<int>)。
例如,调用factorize(12)会返回包含[2, 2, 3]的vector<int>,调用factorize(7)会返回包含[7]的vector<int>
if (x < 2) return factors;
if (x < 2):判断输入的数是否小于 2(覆盖x=0、x=1、负数等情况);
return factors;:直接返回空的factors向量(因为这些数没有质因数,无需分解)
for (int i = 2; i <= x; ++i) {
while (x % i == 0) { // 反复除以i,直到不能整除
factors.push_back(i);
x /= i;
}
i从 2 开始遍历,是否会出现用合数作为除数的情况?
答案是:不会影响结果,因为合数的因数已经被更小的质数提前分解过了,此时x不可能被合数整除。
详细解释:
假设i遍历到一个合数(比如 4),此时x已经被 2、3 等更小的质数分解过了 —— 如果x能被 4 整除,那它必然能被 2 整除(因为 4=2×2),但在i=2的循环中,x已经被反复除以 2,直到无法整除为止。
因此,当i遍历到合数时,x % i == 0的条件永远不会成立,自然不会执行while循环内的分解逻辑。
factors.push_back(i);
factors.push_back(i); 是 C++ 中 vector 容器的成员函数调用,作用是将元素 i 添加到 factors 这个动态数组的末尾。下面从语法、作用、使用场景三方面详细解释:
为什么用while而不用for呢
在质因数分解的逻辑中使用 while 而非 for,是由 “需要反复用同一个因数分解当前数” 的需求决定的 ——while 更适合处理这种 “条件满足时重复执行” 的场景,而 for 更适合 “已知循环次数” 的遍历。下面具体解释:
若强行用 for 替代 while,需要额外控制循环条件,代码会变得冗余且不直观。例如:
// 用for模拟while的逻辑(不推荐)
for (; x % i == 0; x /= i) {factors.push_back(i);}
虽然语法上可行,但 for 的初始化 / 递增部分为空,完全失去了 for 循环 “遍历固定次数” 的设计初衷,可读性反而变差。
vector<int> temp = factorize(i);
虽然factorize函数返回的是一个vector ,但是它没有标记,不好处理,所以在每次循环中都创建一个vector容器。便于使用和操控。
方案二
#include<iostream>
#include<vector>
using namespace std;
int fun1(int m)
{
if (m == 1 || m == 0) { return 1; }
else
{
return m * fun1(m - 1);
}
}
int fun2(int x, int y)
{
int z = fun1(x) * fun1(y);
return z;
}
int main()
{
int a, b, total;
cin >> a >> b;
total = fun2(a, b);
int i, j;
vector<int> vec;
for (i = 2; i <= total; i++)
{
if (total % i == 0)
{
vec.push_back(i);
total /= i;
i--;
}
}
int sum = vec.size();
for (j = 0; j <= sum - 2; j++)
{
cout << vec[j] << "";
}
cout << vec[sum - 1] << endl;
}
#include <iostream>
#include <vector>
using namespace std;
// 计算质数p在n!中的幂次
int countPrimePower(int p, int n) {
int cnt = 0; // 初始化幂次计数器为0
while (n > 0) { // 循环直到n被除到0为止
n /= p; // n = n / p(取整),对应公式中的⌊n/p^k⌋
cnt += n; // 累加每一步的结果,得到总幂次
}
return cnt; // 返回质数p在n!中的总幂次
}
// 判断一个数是否为质数
bool isPrime(int num) {
if (num < 2) return false; // 小于2的数不是质数
// 遍历从2到√num的所有数,检查是否能整除num
for (int i = 2; i * i <= num; ++i) {
if (num % i == 0) return false; // 能被整除则不是质数
}
return true; // 否则是质数
}
int main() {
int a, b; // 定义输入变量a和b
cin >> a >> b; // 从控制台输入两个整数a和b
int max_num = max(a, b); // 获取a和b的最大值,确定质数枚举范围
vector<pair<int, int>> factors; // 定义向量,存储<质数, 幂次>键值对
// 枚举所有质数,计算其在a!b!中的总幂次
for (int p = 2; p <= max_num; ++p) { // 从2枚举到max_num(质数最大不超过max(a,b))
if (isPrime(p)) { // 如果p是质数
// 计算p在a!中的幂次 + p在b!中的幂次 = 总幂次
int power = countPrimePower(p, a) + countPrimePower(p, b);
if (power > 0) { // 若幂次大于0(避免无效存储)
factors.push_back({p, power}); // 将<质数, 幂次>存入向量
}
}
}
// 按格式输出质因数分解结果
for (int i = 0; i < factors.size(); ++i) { // 遍历每个<质数, 幂次>对
int p = factors[i].first; // 获取当前质数
int power = factors[i].second; // 获取当前质数的幂次
for (int j = 0; j < power; ++j) { // 按幂次重复输出质数
// 判断是否是最后一个质数的最后一次输出
if (i == factors.size() - 1 && j == power - 1) {
cout << p; // 最后一个数,不加
} else {
cout << p << ""; // 非最后一个数,加*分隔
}
}
}
cout << endl; // 输出换行,结束
return 0; // 程序正常结束
}
题目描述
编写一个 C++ 程序,实现对非负整数 n 的阶乘(n!)进行质因数分解,并按指定格式输出分解结果。要求:
程序不得使用任何 STL 组件(如 vector、string、algorithm 头文件中的算法等),仅允许使用 C++ 基础语法(数组、循环、条件判断、<iostream>头文件);
质因数分解规则:将 n! 分解为 “质数 ^ 次数” 的乘积形式,次数为 1 时省略 “^1”,多个质因数之间用 “ × ” 分隔;
边界处理:
若输入 n 为负数,输出 “阶乘仅支持非负整数!”;
若 n=0 或 n=1,输出 “0! = 1” 或 “1! = 1”;
质因数筛选要求:高效筛选 1~n 之间的所有质数,统计每个质数在 n! 中出现的总次数(需使用公式:次数 = ⌊n/p⌋ + ⌊n/p²⌋ + ⌊n/p³⌋ + … 直到 p^k > n),禁止暴力计算阶乘后再分解(避免数值溢出)。
输入格式
输入一个整数 n(0 ≤ n ≤ 10000)。
输出格式
若 n 为负数:输出 “阶乘仅支持非负整数!”;
若 n=0 或 n=1:输出 “n! = 1”;
其他情况:输出 “n! = p1^k1 × p2^k2 × ... × pm^km”(次数为 1 时仅输出质数,如 5! = 2^3 × 3 × 5)。
输入输出示例
示例 1
输入:5输出:5! = 2^3 × 3 × 5
示例 2
输入:10输出:10! = 2^8 × 3^4 × 5^2 × 7
示例 3
输入:1输出:1! = 1
示例 4
输入:-3输出:阶乘仅支持非负整数!
示例 5
输入:0输出:0! = 1
解题要求
必须实现isPrime函数判断质数,优化遍历范围至√num;
用数组存储质数和对应次数,替代 STL 的 vector;
严格遵循输出格式(分隔符、次数显示规则、换行等);
代码结构清晰,包含核心功能函数factorizeFactorial,主函数负责输入和调用。
#include <iostream>
using namespace std;
// 函数:判断一个数是否为质数(辅助筛法,也可单独用)
bool isPrime(int num) {
if (num < 2) return false; // 小于2的数不是质数
for (int i = 2; i * i <= num; i++) { // 优化:只需遍历到√num
if (num % i == 0) return false;
}
return true;
}
// 函数:计算n!的质因数分解(无STL)
void factorizeFactorial(int n) {
if (n < 0) {
cout << "阶乘仅支持非负整数!" << endl;
return;
}
if (n == 0 || n == 1) {
cout << n << "! = 1" << endl; // 0!和1!都是1,无质因数
return;
}
// 步骤1:筛选1~n的所有质数
int primes[10000]; // 假设n不超过10000,足够存储质数
int primeCount = 0; // 记录质数的个数
for (int i = 2; i <= n; i++) {
if (isPrime(i)) {
primes[primeCount++] = i; // 找到质数就存入数组
}
}
// 步骤2:统计每个质数在n!中的次数
int counts[10000] = { 0 }; // 存储每个质数的次数,初始化为0
for (int i = 0; i < primeCount; i++) {
int p = primes[i];
int total = 0;
int temp = n;
while (temp > 0) {
temp /= p;
total += temp;
}
counts[i] = total;
}
// 步骤3:输出分解结果(格式:n! = p1^k1 × p2^k2 × ...)
cout << n << "! = ";
for (int i = 0; i < primeCount; i++) {
cout << primes[i];
if (counts[i] > 1) { // 次数>1时输出^k
cout << "^" << counts[i];
}
if (i != primeCount - 1) { // 非最后一个质数,输出×
cout << " × ";
}
}
cout << endl;
}
int main() {
int n;
cout << "请输入要求阶乘质因数分解的数:";
cin >> n;
factorizeFactorial(n);
return 0;
}
冒泡排序
【例4.35】冒泡排序。随机生成10个数,按照由小到大的顺序输出。
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
int nData[10] = {4,10,9,8,7,6,5,4,3,2};
//创建10个数据,测试
for (int i = 0; i < 10; i++){
//从数组尾部检查是否比上面一个小,把小的冒泡浮上去
for (int j = 9; j > i; j--) {
if (nData[j] < nData[j - 1]) {
//如果下面的比上面小,交换
int nTemp = nData[j];
nData[j] = nData[j - 1];
nData[j - 1] = nTemp;
}
}
}
for (int i = 0; i < 10; i++) {
cout.setf(ios::left);
cout<<setw(5)<<nData[i];
}
cout<<endl;
return 0;
}
回文数字
#include <iostream>
using namespace std;
int main() {
int num, original, reversed = 0;
cin >> num;
original = num; // 保存原数字,避免后续操作修改它
// 反转数字
while (num > 0) {
int temp = num % 10; // 取最后一位数字
reversed = reversed * 10 + temp; // 把数字拼到反转结果里
num = num / 10; // 去掉最后一位
}
// 比较原数字和反转后的数字
if (original == reversed) {
cout << "yes" << endl;
} else {
cout << "no" << endl;
}
return 0;
}
#include<iostream>
#include<string>
using namespace std;
bool huiwen(int n) {
string s = to_string(n); // 将数字转为字符串,方便判断回文
int len = s.size();
for (int i = 0; i < len / 2; i++) {
if (s[i] != s[len - 1 - i]) { // 比较对称位置的字符
return false;
}
}
return true;
}
int main() {
int a;
cin >> a;
cout << (huiwen(a) ? "yes" : "no") << endl;
return 0;
}
杨辉三角
#include <iostream>
#include <vector>
using namespace std;
// 函数功能:生成并打印n阶杨辉三角
// 参数n:杨辉三角的行数(用户输入的正整数)
void yanghui(int n) {
// 初始化二维vector:(n+4)行 × (n+4)列,所有元素默认值为0
// 额外多分配4行4列是为了避免边界访问风险(无需精确计算行列上限,简单直接)
vector<vector<int>> res(n + 4, vector<int>(n + 4));
// 第一步:填充每行的第一个元素(第0列)为1
// 杨辉三角特性:每行首尾元素均为1,第0列是所有行的首元素
for (int i = 0; i <= n - 1; i++) { // i遍历所有行(0到n-1,共n行)
res[i][0] = 1; // 第i行第0列赋值为1
}
// 第二步:填充每行的最后一个元素(对角线位置)为1
// 第i行的最后一个元素索引是i(因为第i行有i+1个元素,索引0~i)
for (int i = 1; i <= n - 1; i++) { // i从1开始(第0行只有1个元素,已在第一步赋值)
res[i][i] = 1; // 第i行第i列(对角线)赋值为1
}
// 第三步:计算每行的中间元素(核心逻辑)
// 中间元素 = 上一行前一列元素 + 上一行当前列元素
for (int i = 2; i <= n - 1; i++) { // i从2开始(第0、1行无中间元素,已完整填充)
// j遍历当前行的中间列(1到i-1,跳过首尾的1)
for (int j = 1; j <= i - 1; j++) {
res[i][j] = res[i - 1][j] + res[i - 1][j - 1]; // 杨辉三角核心公式
}
}
// 第四步:打印杨辉三角
for (int i = 0; i <= n - 1; i++) { // 遍历每一行
// 只打印当前行的有效元素(0到i列,共i+1个元素)
for (int j = 0; j <= i; j++) {
cout << res[i][j] << " "; // 元素间用空格分隔,提升可读性
}
cout << endl; // 一行打印完毕,换行
}
}
int main() {
int m;
cin >> m;
yanghui(m); // 调用函数,生成并打印m阶杨辉三角
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
// 生成n阶杨辉三角的函数,返回二维vector存储结果
vector<vector<int>> generateYanghui(int n) {
// 初始化n行的二维vector,每行初始为空
vector<vector<int>> triangle(n);
for (int i = 0; i < n; ++i) {
// 第i行有i+1个元素,先全部初始化为1(满足首尾为1的特性)
triangle[i].resize(i + 1, 1);
// 计算中间元素(从第2行开始,i≥2)
for (int j = 1; j < i; ++j) {
triangle[i][j] = triangle[i-1][j-1] + triangle[i-1][j];
}
}
return triangle;
}
int main() {
int n;
cin >> n; // 输入行数
// 调用函数生成杨辉三角
vector<vector<int>> result = generateYanghui(n);
// 输出结果(匹配样例格式,元素间空格分隔)
for (const auto& row : result) {
for (int num : row) {
cout << num << " ";
}
cout << endl;
}
return 0;
}
Eratosthenes 筛法素数
使用Eratosthenes 筛法求1000以内的素数
• 将1~1000放在数组sieve(看成是一个筛子)中
• 首先“留下”2(第一个素数),而后把2的倍数统统从数组sieve(筛子)中删去
• 再“留下”3(第二个素数),而后把3的倍数统统从数组sieve中删去;
• 再往下是5,7,...。好像是一个筛子,把不需要的数逐步筛去,留下的正是所需要的各素数
• 所谓将某数从数组sieve(筛子)中删去,本程序实现时,是将数组中的该数“改写”为0
#include<iomanip>
#include<iostream>
using namespace std;
int main() {
const int n=1000;
int sieve[n+1];
//筛子sieve
for(int j=1; j<n+1; j++)
sieve[j]=j;
//放入数据
int i=1, count=0;
while(i<n) {
i++;
if(sieve[i]!=0 ){
//尚在筛中
cout<<setw(5)<<sieve[i];
count++;
if(count%15==0)
cout<<endl;
//每行15数
for(int k=i;k<n+1; k+=i)//消去倍数
sieve[k]=0;
}
//if
}
// while
cout<<endl;
return 0;
}
//main
求正整数各位数
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector <int> aa;
int n;
cin >> n;
while (n > 0)
{
aa.push_back(n % 10);
n /= 10;
}
for (int aaa : aa)
{
cout << aaa << " ";
}
//范围 for 循环”(也叫增强 for 循环);
//语法:for (元素类型 变量名 : 容器名),
//每次循环会把容器中的一个元素赋值给变量;
//这里int aaa表示 “定义临时变量 aaa,
//每次取 aa 中的一个 int 元素”,循环次数等于 aa 的元素个数。
return 0;
}
注:此代码为逆序后的结果
strcat_s()函数
这个函数没用到引用,却能修改主函数里的数组a,核心原因是:数组名作为函数参数时,会自动 “退化为指向数组首元素的指针”—— 传递的不是数组拷贝,而是数组的内存地址,函数内通过地址直接操作原数组内存。
#include<iostream>
using namespace std;
void strcat(char s[], char ct[])
{
int i = 0, j = 0;
while (s[i] != 0)
i++;
// 第一步:找到字符串s的末尾('\0'的位置)
// '\0'是C风格字符串的结束标志,ASCII码值为0,所以s[i] != 0等价于s[i] != '\0'
while (ct[j] != 0)
s[i++] = ct[j++];
// 把ct[j]赋值给s[i],然后i、j同时自增(先赋值,后自增)
s[i] = '\0';
//给拼接后的s添加结束符'\0'
// 否则cout打印时会超出数组范围,输出乱码
}
int main() {
char a[40] = "李明";
char b[20] = "是南开大学学生";
strcat(a, b);//实参为数组名
cout << a << endl;//打印字符数组a
return 0;
}
矩阵+素数
注意边界处理
#include<iostream>
using namespace std;
bool isprime(int n) {
if (n < 2) {return false;}
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) {
return false;
}
}
return true;
}
int main() {
int m, n;
cin >> m >> n;
int* test = new int[m * n];
for (int i = 0; i < m * n; i++) { cin >> test[i]; }
for (int i = 0; i < m * n; i++) {
for (int j = m * n - 1; j > i; j--) {
if (test[j] < test[j - 1]) {
int tem = test[j];
test[j] = test[j - 1];
test[j - 1] = tem;
}
}
}
for (int i = 0; i < m * n; i++) {
if (isprime(test[i])) {
int res = i + 1;;
int col = res % n;
if (col == 0) { col = n; }
int row = i / n + 1;
cout << row << ' ' << col;
break;
}
}
}
八里台的树
#include<iostream>
using namespace std;
int main() {
int L, M;
cin >> L >> M;
int* p = new int[L+1];
for (int i = 0; i < L + 1; i++) {
p[i] = 1;
}
for (int j = 0; j < M; j++) {
int begin, end;
cin >> begin >> end;
for (int i = begin; i <= end; i++) {
p[i] = 0;
}
}
int count=0;
for (int z = 0; z <= L; z++) {
if (p[z] == 1) {
count++;
}
}
cout << count;
}
排列数组合数
【例5.16】三色冰淇淋程序由冰激凌商提出的问题 :有28种颜色的原料,可以组合成多少种3色冰激凌
• 问题归结为计算排列数与组合数。本示例计算排列数
A(elements,selections)及组合数
C(elements,selections)。如:
A(3,2)=6, C(3,2)=3;
A(28,3)=19656, C(28,3)=3276。
计算阶乘的函数定义
long factorial(int number)
{
long value = 1;
while(number>1){
value = number;
number--;
}
return value;
}
#include <iostream>
using namespace std;
long factorial(int number); //函数原型
int main(){
int i,selections,elements;
//计算A(elements,selections)
//以及C(elements,selections)
cout<<"Number of selections:";
cin>>selections; //输入整数selections
cout<<"Out of how many elements:";
cin>>elements; //输入整数elements
double answer ;
answer = factorial(elements) / factorial
(elements-selections);
cout<<"A("<<elements<<","<<selections<<")="<<a
nswer<<endl;
//输出排列数A(ele,sel)之结果
//组合数C的求法:
answer/=factorial(selections);
cout<<"C("<<elements<<","<<selections<<")="<<a
nswer<<endl; //输出组合数C(ele,sel)之结果
return 0;
}
字符串中的字母查找
提示用户输入任意一个字符串和一个字符c,而后找到输入串中第一个c字符出现的位置(若有的话),并输出从c字符开始的子串; 若输入串中不出现c字符的话, 输出 “No match found”。
#include<iostream>
using namespace std;
char match(char c, char ch[]);
int main() {
cout << "input a string and a char" << endl;
char ch[100];
char c;
cin.getline(ch, 100);
cin >> c;
char* p = match(c, ch);
if (p != nullptr) {
cout << p;
}
if (p == nullptr) {
cout << "No match found";
}
}
char* match(char c, char ch[]) {
int i = 0;
while (ch[i] != c && ch[i] != '\0') {
i++;
}
if (ch[i] == c) { return &ch[i]; }
else { return nullptr; }
}
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
char c;
cout << "请输入一个字符串(可含空格):" << endl;
getline(cin, str);
cout << "请输入需要查找的单个字符:" << endl;
cin >> c;
// 3. 查找第一个c的索引
size_t idx = str.find(c);
if (idx != string::npos) {
cout << str.substr(idx) << endl; // 输出子串 + 换行符
} else {
cout << "No match found" << endl; // 加换行符,格式更美观
}
return 0;
}
ascii码表对应输入输出
#include<iostream>
using namespace std;
int main()
{
char ch=77;
cout << ch << endl;//输入ascii值,输出对应字符
char cha = 'A';
cout << (int) (cha) << endl;//输入字符,输出对应ascii值
int a = '5';
cout << a << endl;//输入字符,输出对应ascii值
int b= 5;
cout << b << endl;
}
(‘5’表示数字5这个字符)
#include<iostream>
using namespace std;
int main()
{
int a =' 3';
if (a < 50) { cout << "ok" << endl; }
else { cout << "okk" << endl; }
}
在这个代码中,
int a=3 认为是整数3int a='3' 认为是字符3,整数变量a存储值为51char a='3'认为是字符3, cout char类型时显示字符本身3,cput int类型时显示、ASCII值51.
用指针排序字符串
设计一个字符指针数组name,将该数组的元素按照第一个字母的ASCII码由小到大排序,如果第一个字母相同,则按第二个字母排序,以此类推。
#include <iostream>
#include <cstring> // 包含strcmp函数
using namespace std;
int main() {
// 1. 定义并初始化字符指针数组(存储待排序的字符串)
char* name[] = {"Zhang", "Gao", "Tang", "Wang", "Li", "Gou", "Zhao"};
// 计算数组长度(元素个数)
int len = sizeof(name) / sizeof(name[0]);
// 2. 冒泡排序:按ASCII码逐字符升序排列
for (int i = 0; i < len - 1; i++) { // 外层循环:控制排序轮数
for (int j = 0; j < len - 1 - i; j++) { // 内层循环:每轮比较次数
// strcmp(a,b):a>b返回正数,a==b返回0,a<b返回负数
// 若name[j] > name[j+1],交换指针指向(升序)
if (strcmp(name[j], name[j+1]) > 0) {
char* temp = name[j];
name[j] = name[j+1];
name[j+1] = temp;
}
}
}
// 3. 输出排序结果
cout << "排序后的字符串:" << endl;
for (int i = 0; i < len; i++) {
cout << name[i] << endl;
}
return 0;
}
#include <iostream>
#include <cstring>
#include <algorithm> // 包含sort函数
using namespace std;
int main() {
char* name[] = {"Zhang", "Gao", "Tang", "Wang", "Li", "Gou", "Zhao"};
int len = sizeof(name) / sizeof(name[0]);
// sort算法 + Lambda表达式:自定义比较规则(升序)
sort(name, name + len, [](const char* a, const char* b) {
// strcmp(a,b) < 0 表示a的ASCII码小于b,a应排在b前面
return strcmp(a, b) < 0;
});
// 输出结果
cout << "排序后的字符串:" << endl;
for (int i = 0; i < len; i++) {
cout << name[i] << endl;
}
return 0;
}
函数指针求积分
#include <iostream>
#include <cmath> // 用于exp等数学函数
using namespace std;
// 定积分计算函数(梯形法)
// 参数:a-积分下限,b-积分上限,fun-被积函数指针
double integral(double a, double b, double (*fun)(double)) {
// 梯形法:将区间[a,b]分成n个小区间,n越大精度越高
const int n = 100000; // 区间分割数(可调整)
double h = (b - a) / n; // 每个小区间的宽度
double sum = 0.5 * (fun(a) + fun(b)); // 首尾项的平均
// 累加中间点的函数值
for (int i = 1; i < n; ++i) {
double x = a + i * h;
sum += fun(x);
}
return sum * h; // 梯形法公式:h * (sum)
}
// 被积函数1:f(x) = 1 + x
double f1(double x) {
return 1 + x;
}
// 被积函数2:f(x) = 2x + 3
double f2(double x) {
return 2 * x + 3;
}
// 被积函数3:f(x) = e^x + 1
double f3(double x) {
return exp(x) + 1;
}
// 被积函数4:f(x) = (1 + x)^2
double f4(double x) {
return (1 + x) * (1 + x);
}
// 被积函数5:f(x) = x^3
double f5(double x) {
return pow(x, 3);
}
int main() {
double a, b;
cout << "请输入积分下限a和上限b(用空格分隔):";
cin >> a >> b;
// 计算并输出5个定积分的结果
cout << "∫(" << a << "," << b << ") (1+x)dx = " << integral(a, b, f1) << endl;
cout << "∫(" << a << "," << b << ") (2x+3)dx = " << integral(a, b, f2) << endl;
cout << "∫(" << a << "," << b << ") (e^x+1)dx = " << integral(a, b, f3) << endl;
cout << "∫(" << a << "," << b << ") (1+x)^2dx = " << integral(a, b, f4) << endl;
cout << "∫(" << a << "," << b << ") x^3dx = " << integral(a, b, f5) << endl;
return 0;
}
模拟题1龟兔赛跑
#include<iostream>
using namespace std;
int main()
{
int x=0,y=0;
int T;
cin>>T;
for(int i=1;i<=T;i++)
{y+=3;}
for(int i=1;i<=T;i++)
{x+=9;
bool t=(x>(3*i));
if(i%10==0&&t==1)
{i+=30;}}
if(x>y){cout<<"^^"<<" "<<x<<endl;}
else{if(x==y){cout<<"--"<<" "<<x<<endl;}
else{cout<<"@@"<<" "<<y<<endl;}}
return 0;
}
#include<iostream>
#include<cmath>
using namespace std;
int main() {
int rabbit=0, turtle=0, T;
cin >> T;
int timepast = 0;
while (timepast < T) {
int res = min(10, T - timepast);
rabbit += 9 * res;
timepast += res;
if (timepast >= T) { break; }
int turtletem = 3 * timepast;
if (rabbit > turtletem) {
int res = min(30, T - timepast);
timepast += res;
}
if (timepast >= T) { break; }
}
turtle = 3 * T;
if (turtle > rabbit) { cout << "@@" << " " << turtle; }
else if (turtle == rabbit) { cout << "--" << " " << turtle; }
//判断是否相等不要再写成=了
else { cout << "^^" << " " << rabbit; }
}
模拟题2转换字符
数字字符:'0'=48 < '1'=49 < ... < '9'=57
大写字母:'A'=65 < 'B'=66 < ... < 'Z'=90
小写字母:'a'=97 < 'b'=98 < ... < 'z'=122
空格:' '=32(比数字、字母都小)
小写字母 → 转大写(ASCII 减 32)
字符类型(char)可以直接比较大小
#include<iostream>
#include<string>
#include<cctype> // 包含 isalpha() 函数
using namespace std;
int main() {
string str;
getline(cin, str); // 支持输入含空格的字符串(比如 "abc 123 def")
for (size_t i = 0; i < str.size(); i++) {
if (!isalpha(str[i])) { // isalpha(c):判断 c 是否为字母(大小写都算)
str[i] = ' '; // 非字母 → 空格
} else if (islower(str[i])) { // islower(c):判断 c 是否为小写字母
str[i] = toupper(str[i]); // toupper(c):将小写字母转大写(自带判断,更安全)
}
// 大写字母无需处理,直接保留
}
cout << str << endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main() {
string str;
getline(cin, str); // 支持输入含空格的字符串(比如 "abc 123 def")
// 遍历字符串每个字符
for (size_t i = 0; i < str.size(); i++)
{
char c = str[i];
// 直接判断:既不是大写字母,也不是小写字母 → 非字母||或是并集@是交集借助维恩图理解;
if ((c < 'A' || c > 'Z') && (c < 'a' || c > 'z'))
{
str[i] = ' '; // 替换为空格
}
// 2. 判断是否为小写字母 → 转大写(ASCII 减 32)
else if (c >= 'a' && c <= 'z') {
str[i] = c - 32; // 例如 'a'(97)-32=65='A'
}
// 3. 大写字母无需处理,直接保留
}
cout << str << endl;
return 0;
}
#include<iostream>
#include<string>
using namespace std;
int main()
{
string str;
cin >> str;
size_t len = str.size();
for (int i = 0; i < len; i++)
{
if ((str[i] < 'A' || str[i]>'Z') && (str[i] < 'a' || str[i]>'z'))
{
str[i] = ' ';
}
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] -= 32;
}
}
cout << str << endl;
}
#include<iostream>
using namespace std;
int main() {
char test[50];
cin >> test;
for (int i = 0; test[i] != '\0'; i++) {
if (test[i] <= 'Z' && test[i] >= 'A') {
test[i] += 32; cout << test[i];
continue;
}
if (test[i] <= 'z' && test[i]>='a') {
test[i] -= 32; cout << test[i];
continue;
}
}
}
注意边界效应,比如这个大写字母是>=而不是>
第二个if语句改成ifelse可以避免重复判断而加continue
小心在是否为连续数字的判断中,判断条件中的自增与自减会改变循环计数i的值
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char test[50] = {'\0'};
cin >> test;
for (int i = 0; i < strlen(test); i++) {
if (test[i] >= 'a' && test[i] <= 'z') {
test[i] -= 32;
cout << test[i];
}
else if (test[i] >= '0' && test[i] <= '9') {
int res = i,res1=i,res2=i;
while (test[++res] >= '0' && test[++res1] <= '9') { i++; }
for (int j = i; j >= res2; j--) { cout << test[j]; }
}
else if (test[i] >= 'A' && test[i] <= 'Z') { cout << test[i]; }
else { cout << test[i] << test[i]; }
}
cout << endl;
}
模拟题3矩阵运算
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n;
cin >> n;
if (n > 9 || n < 1) { cout << "WRONG"; return 0; }
vector<vector<int>>a(n, vector<int>(n));
vector<vector<int>>b(n, vector<int>(n));
vector<vector<int>>c(n, vector<int>(n));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin>> a[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cin>>b[i][j];
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
int s = 0;
for (int z = 0; z < n; z++) { s += a[i][z] * b[z][j]; }
c[i][j] = s;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
cout << c[i][j];
if (j != n - 1) cout << " ";
}
cout << endl;
}
}
#include <iostream>
#include <cstring> // 用于字符串复制
using namespace std;
// 定义选手结构体
struct Player
{
char name[50]; // 存储姓名(原生字符数组,不使用string)
int score; // 存储最终得分
};
// 计算单个选手的最终得分(去掉高低分后求和)
int calculateScore(int scores[])
{
int sum = 0;
int max = scores[0], min = scores[0];
// 遍历7个分数,求和、找最大最小
for (int i = 0; i < 7; ++i) {
sum += scores[i];
if (scores[i] > max) max = scores[i];
if (scores[i] < min) min = scores[i];
}
return sum - max - min; // 去掉高低分后的总分
}
// 选择排序函数(按得分从高到低排序,不使用STL算法)
void sortPlayers(Player players[], int n)
{
for (int i = 0; i < n - 1; ++i) {
int maxIdx = i;
// 找到当前未排序部分的最高分下标
for (int j = i + 1; j < n; ++j) {
if (players[j].score > players[maxIdx].score) {
maxIdx = j;
}
}
// 交换当前元素和最高分元素,直接把姓名跟着一起交换了
Player temp = players[i];
players[i] = players[maxIdx];
players[maxIdx] = temp;
}
}
int main() {
int n;
cin >> n;
// 定义原生数组存储选手信息(不使用vector)
Player players[100]; // 假设最多100名选手,满足题目输入需求
// 读取每个选手的信息
for (int i = 0; i < n; ++i)
{
int scores[7]; // 创建一个临时数组,用来存储7个评委分数
cin >> players[i].name; // 读取姓名
// 读取7个分数
for (int j = 0; j < 7; ++j) {
cin >> scores[j];
}
// 计算并存储最终得分
players[i].score = calculateScore(scores);
}
// 排序选手(从高到低)
sortPlayers(players, n);
// 输出结果
for (int i = 0; i < n; ++i) {
cout << players[i].name << " " << players[i].score << endl;
}
return 0;
}
模拟题4比赛评分
#include<iostream>
using namespace std;
struct player {
char name[50];
int score;
};
int calculation(int a[]) {//输入的形参可以随便起名
int sum=0;
for (int j = 0; j < 7; j++) {
sum += a[j];
}int max = a[0], min = a[0];
for (int i = 1; i < 7; i++) {
if (a[i] > max) { max = a[i]; }
if (a[i] <min) { min = a[i]; }
}
return sum = sum - max - min;
}//冒泡排序
void sortplayer(player b[], int c) {
for (int i = 0; i < c; i++) {
for(int j=c-1;j>i;j--){
if (b[j].score > b[j - 1].score) {
player tem = b[j];//直接将整个player结构交换
b[j] = b[j - 1];
b[j - 1] = tem;
}
}
}
}
int main(){
int n;
cin >> n;
player PLAYER[100];定义一个结构类型的数组,储存所有参赛人员数据
for (int i = 0; i < n; i++) {
cin >> PLAYER[i].name;
int initialscore[7];
for (int j = 0; j < 7; j++) {
cin >> initialscore[j];
}
PLAYER[i].score = calculation(initialscore);
}
sortplayer(PLAYER, n);
for (int i = 0; i < n; i++) {
cout << PLAYER[i].name << " " << PLAYER[i].score ;
if (i != n - 1) { cout << endl; }
}
}
字符串旋转
#include <iostream>
#include <string>
using namespace std;
int main() {
int N,w;
cin >> N;
w = N;
while (N--)
{
string S;
char M;
int n;
cin >> S >> M >> n;
int len = S.size();
string res = S; // 默认无效操作时为原字符串
if (M == 'L') {
n %= len; // 处理n超过长度的情况
res = S.substr(n) + S.substr(0, n);
}
else if (M == 'R') {
n %= len;
res = S.substr(len - n) + S.substr(0, len - n);
}
// 提取奇数位置的字符(注意:题目中位置是从1开始计数)
string ans;
for (int i = 0; i < res.size(); ++i)
{
if (i % 2 == 0) { // 第1、3、5...位对应索引0、2、4...
ans += res[i];
}
}
if(w>1) { cout << ans << endl; }else{ cout << ans ; }
w = w - 1;
}
return 0;
}
学生结构体
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
string id; // 学号
string name; // 姓名
double math; // 数学成绩
double chinese; // 语文成绩
double english; // 英语成绩
};
int main() {
int n;
cin >> n;
if (n < 1 || n > 100) { // 班级最多100人
return 1;
}
vector<Student> students(n);
// 输入n个学生的信息
for (int i = 0; i < n; ++i) {
cin >> students[i].id >> students[i].name
>> students[i].math >> students[i].chinese >> students[i].english;
}
int sort_type;
cin >> sort_type;
// 检查排序依据是否合法
if (sort_type != 1 && sort_type != 2 && sort_type != 3) {
cout << "ERROR" << endl;
return 0;
}
// 定义排序规则:科目降序,成绩相同则学号升序
sort(students.begin(), students.end(), [sort_type](const Student& a, const Student& b) {
if (sort_type == 1) { // 数学成绩排序
if (a.math != b.math) {
return a.math > b.math; // 数学降序
}
} else if (sort_type == 2) { // 语文成绩排序
if (a.chinese != b.chinese) {
return a.chinese > b.chinese; // 语文降序
}
} else { // 英语成绩排序
if (a.english != b.english) {
return a.english > b.english; // 英语降序
}
}
// 成绩相同时,学号升序
return a.id < b.id;
});
// 输出排序后的学号和姓名
for (const auto& s : students) {
cout << s.id << " " << s.name << endl;
}
return 0;
}
学生结构体
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
struct student {
char number[30];
char name[30];
double math;//注意成绩有小数点不能用int类型
double chinese;
double english;
};
int main() {
int n;
cin >> n;
student STUDENT[100];
for (int i = 0; i < n; i++)
{
cin >> STUDENT[i].number >> STUDENT[i].name
>> STUDENT[i].math >> STUDENT[i].chinese >> STUDENT[i].english;
}
int rule;
cin >> rule;
if (rule != 1 && rule != 2 && rule != 3) { cout << "ERROR"; return 0; }//注意是&&
if (rule == 1)
{
for (int i = 0; i < n; i++)
{
for (int j = n - 1; j > i; j--)
{
if (STUDENT[j].math > STUDENT[j - 1].math)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
else if (STUDENT[j].math == STUDENT[j - 1].math)
{//char类型的数组不能直接比较
if (strcmp(STUDENT[j].number, STUDENT[j-1].number) < 0)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
}
}
}
}
else if (rule == 2)
{
for (int i = 0; i < n; i++)
{
for (int j = n - 1; j > i; j--)
{
if (STUDENT[j].chinese > STUDENT[j - 1].chinese)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
else if (STUDENT[j].chinese == STUDENT[j - 1].chinese)
{
if (strcmp(STUDENT[j].number, STUDENT[j - 1].number) < 0)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
}
}
}
}
else if (rule == 3)
{
for (int i = 0; i < n; i++)
{
for (int j = n - 1; j > i; j--)
{
if (STUDENT[j].english > STUDENT[j - 1].english)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
else if (STUDENT[j].english == STUDENT[j - 1].english)
{
if (strcmp(STUDENT[j].number, STUDENT[j - 1].number) < 0)
{
student tem = STUDENT[j];
STUDENT[j] = STUDENT[j - 1];
STUDENT[j - 1] = tem;
}
}
}
}
}
for (int i = 0; i < n; i++) {
cout << STUDENT[i].number << STUDENT[i].name << endl;
}
}
#include <iostream>
#include <vector>
#include <algorithm>
#include <string>
using namespace std;
// 定义学生结构体
struct Student {
string id; // 学号
string name; // 姓名
double math; // 数学成绩
double chinese; // 语文成绩
double english; // 英语成绩
};
int main() {
int n;
cin >> n;
if (n < 1 || n > 100) { // 班级最多100人
return 1;
}
vector<Student> students(n);
// 输入n个学生的信息
for (int i = 0; i < n; ++i) {
cin >> students[i].id >> students[i].name
>> students[i].math >> students[i].chinese >> students[i].english;
}
int sort_type;
cin >> sort_type;
// 检查排序依据是否合法
if (sort_type != 1 && sort_type != 2 && sort_type != 3) {
cout << "ERROR" << endl;
return 0;
}
// 定义排序规则:科目降序,成绩相同则学号升序
sort(students.begin(), students.end(), [sort_type](const Student& a, const Student& b) {
if (sort_type == 1) { // 数学成绩排序
if (a.math != b.math) {
return a.math > b.math; // 数学降序
}
} else if (sort_type == 2) { // 语文成绩排序
if (a.chinese != b.chinese) {
return a.chinese > b.chinese; // 语文降序
}
} else { // 英语成绩排序
if (a.english != b.english) {
return a.english > b.english; // 英语降序
}
}
// 成绩相同时,学号升序
return a.id < b.id;
});
// 输出排序后的学号和姓名
for (const auto& s : students) {
cout << s.id << " " << s.name << endl;
}
return 0;
}
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct student {
string idx;
string name;
double math;
double chinese;
double english;
};
int main() {
int n;
cin >> n;
vector <student> STUDENT;
for (int i = 0; i < n; i++) {
student tem;
cin >> tem.idx >> tem.name >> tem.math >> tem.chinese >> tem.english;
STUDENT.push_back(tem);
}
int rule;
cin >> rule;
if (rule == 1) {
sort(STUDENT.begin(), STUDENT.end(), [](const student& a, const student& b) {
if (a.math != b.math) { return a.math > b.math; }
else { return a.idx < b.idx; }
});
}
else if (rule == 2) {
sort(STUDENT.begin(), STUDENT.end(), [](const student& a, const student& b) {
if (a.chinese != b.chinese) { return a.chinese > b.chinese; }
else { return a.idx < b.idx; }
});
}
else if (rule == 3) {
sort(STUDENT.begin(), STUDENT.end(), [](const student& a, const student& b) {
if (a.english != b.english) { return a.english > b.english; }
else { return a.idx < b.idx; }
});
}
else { cout << "ERROR"; return 0; }
for (int i = 0; i < n; i++) {
if(i!=n-1){ cout << STUDENT[i].idx << " " << STUDENT[i].name << endl; }
else if(i==n-1) { cout << STUDENT[i].idx << " " << STUDENT[i].name ; }
}
}
数组合并
#include<iostream>
using namespace std;
// 冒泡排序函数:对int类型数组进行升序排序
// 参数1 sum[]:待排序的数组(本质是数组首元素的指针,会直接修改原数组)
// 参数2 size:数组中有效元素的个数(避免越界访问)
void sort(int sum[], int size) {
for (int i = 0; i < size; i++) {
for (int j = size - 1; j > i; j--) {
if (sum[j] < sum[j - 1]) {
int temp = sum[j];
sum[j] = sum[j - 1];
sum[j - 1] = temp;
}
}
}
}
int main() {
int sum[200], m, n, size;
cin >> m >> n;
size = m + n;
for (int i = 0; i < m; i++) {
cin >> sum[i];
}
for (int i = 0; i < n; i++) {
cin >> sum[m + i];
}
// 调用排序函数:传数组名sum(退化为指针)和有效长度size
sort(sum, size);
// 去重输出相关:
// isFirst:标记是否是第一个要输出的元素(用于控制空格,避免末尾多空格)
bool isFirst = true;
for (int i = 0; i < size; i++) {
if (i == 0 || sum[i] != sum[i - 1]) {
if (!isFirst) {cout << " ";}
cout << sum[i];
isFirst = false;
}
}
return 0;
}
数组合并:int类型数组没有好用的函数如strlen(),数组合并的难题用直接输入一个大数组来解决
删除重复:利用排序后重复的数字相邻,使用for循环只输出第一个数和与前面的数字不同的元素
格式问题:将每个元素与其前面的空格视为一次循环,只需要考虑第一个元素,避免了末尾的空格问题;
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int M, N;
cin >> M >> N;
vector<int> arr(M + N);
int index = 0;
// 读取第一个数组
for (int i = 0; i < M; i++) {
cin >> arr[index];
index++;
}
// 读取第二个数组
for (int i = 0; i < N; i++) {
cin >> arr[index];
index++;
}
// 使用set自动去重和排序
set<int> s(arr.begin(), arr.end());
// 输出结果
bool first = true;
for (int num : s) {
if (!first) {
cout << " ";
}
cout << num;
first = false;
}
cout << endl;
return 0;
}
矩阵运算
#include <iostream>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
int matrix[10][10];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> matrix[i][j];
}
}
// --- 矩形输出(蛇形行遍历) ---
for (int i = 0; i < m; i++) {
bool isfirst = true;
if (i % 2 == 0) {
for (int j = 0; j < n; j++) {
if (isfirst != true) { cout << " "; }
cout << matrix[i][j];
isfirst = false;
}
}
else { // 奇数行:从右到左
for (int j = n - 1; j >= 0; j--) {
if (isfirst != true) { cout << " "; }
cout << matrix[i][j];
isfirst = false;
}
}
}
cout << endl;
// --- 回转输出(顺时针螺旋) ---
int top = 0, bottom = m - 1, left = 0, right = n - 1;
int count = 0;
int total = m * n;
while (count < total) {
// 向右
for (int j = left; j <= right && count < total; j++) {
cout << matrix[top][j];
count++;
if (count < total) cout << " ";
}
top++;
// 向下
for (int i = top; i <= bottom && count < total; i++) {
cout << matrix[i][right];
count++;
if (count < total) cout << " ";
}
right--;
// 向左
for (int j = right; j >= left && count < total; j--) {
cout << matrix[bottom][j];
count++;
if (count < total) cout << " ";
}
bottom--;
// 向上
for (int i = bottom; i >= top && count < total; i--) {
cout << matrix[i][left];
count++;
if (count < total) cout << " ";
}
left++;
}
return 0;
}
#include<iostream>
using namespace std;
int main()
{
int m, n;
cin >> m >> n;
int a[10][10];
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
cin >> a[i][j];
}
}
for (int i = 0; i < m; i++)
{
if (i % 2 == 0)
{
for (int j = 0; j < n; j++)
{
cout << a[i][j]<<" ";
}
}
else
{
for (int j = n - 1; j >= 0; j--)
{
cout << a[i][j]<<" ";
}
}
}
cout << endl;
for (int k = 0; k < (m + 1) / 2; k++)
{
if (k == n - k - 1)
{
for (int i = k; i <= m - k - 1; i++)
{
cout << a[i][(n + 1) / 2-1] << " ";
}
break;
}
if (n % 2 == 0&&m%2==0 && k == (m + 1) / 2 - 1) { break; }
for (int j = k; j < n-k; j++)
{
cout << a[k][j] << " ";
}
if (m % 2 != 0 && k == (m + 1) / 2 - 1) { break; }
for (int i = 1+k; i < m-k; i++)
{
cout << a[i][n - 1-k] << " ";
}
for (int j = n - 2-k; j >= k; j--)
{
cout << a[m - 1-k][j] << " ";
}
if (m % 2 == 0 && k == (m + 1) / 2-1) { break; }
for (int i = m - 2-k; i >= 1+k; i--)
{
cout << a[i][k] << " ";
}
}
return 0
距离最近的素数
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
int main() {
vector<int>prime = {2,3};
for (int i = 4; i <= 1000000; i++) {
bool isprime = true;
for (int j = 2; j <= sqrt(i); j++) {
if (i % j == 0) {isprime = false; break;}
}
if (isprime) { prime.push_back(i); }
}//创建包含2到1000000的全部素数的vector容器
int N;
cin >> N;
if (N <= 0 || N > 10000) { cout << "INCORRECT INPUT!"; return 0; }
for (int z = 0; z < N; z++)
{
int tem;
cin >> tem;
if (tem <= 0 || N > 1000000) { cout << "INCORRECT INPUT!"; return 0;}
int MIN=-2,MAX;
int shortlen;
int shortprime;
for (int i = 0;; ) {
if (prime[i] < tem) {
MIN = prime[i]; i++; continue;
}
else if (prime[i] == tem) { MAX = prime[i]; MIN = prime[i]; break;}
else if (prime[i] > tem) { MAX = prime[i]; break; }
}
shortlen=min(MAX - tem, tem - MIN);
if ((MAX - tem) < (tem - MIN)) { shortprime = MAX; }
else if ((MAX - tem) > (tem - MIN)) { shortprime = MIN; }
else if((MAX - tem) ==(tem - MIN)) { shortprime = MIN; }
cout << shortprime << ' ' << shortlen ;
if (z != N - 1) { cout << endl; }
}
}
重载函数
逆向思维遍历ASCII码,反过来对应字符,既实现了排序又避免了重复计数。
#include<iostream>
#include<algorithm>
#include<cmath>
#include<vector>
#include<cstring>
using namespace std;
void oddFilter(int a[],int size)
{
vector <int> veca;
for(int i=0;i<size;i++)
{
if(a[i]%2!=0)
{
veca.push_back(a[i]);
}
}
if(veca.size()==0)
{
cout<<"No Odd!"<<endl;
}
else{
sort(veca.begin(),veca.end());
for(int i=0;i<veca.size();i++)
{
cout<<veca[i];
if(i<veca.size()-1)
{
cout<<" ";
}
}
cout<<endl;}
}//
void oddFilter(double b[],int size)
{
vector <int> transform;
vector <int> vecb;
for(int i=0;i<size;i++)
{
int tran=nearbyint(b[i]);
transform.push_back(tran);
}
for(int i=0;i<transform.size();i++)
{
if(transform[i]%2!=0)
{
vecb.push_back(transform[i]);
}
}
if(vecb.size()==0)
{
cout<<"No Odd!"<<endl;
}
else{
sort(vecb.begin(),vecb.end());
for(int i=0;i<vecb.size();i++)
{
cout<<vecb[i];
if(i<vecb.size()-1)
{
cout<<" ";
}
}
cout<<endl;}
}//
void oddFilter(char c[],int size)
{
int ascii[128];
vector <int> ctran;
vector <int> vecchar;
for(int i=0;i<128;i++)
{
ascii[i]=i;
}
for(int i=0;i<size;i++)
{
int zc=(int) c[i];
ctran.push_back(zc);
}
for(int i=0;i<128;i++)
{
int count=0;
for(int j=0;j<ctran.size();j++)
{
if(ctran[j]==ascii[i])
{
count++;
}
}
if(count%2!=0)
{
vecchar.push_back(ascii[i]);
}
}
if(vecchar.size()==0)
{
cout<<"No Odd!";
}
else{
sort(vecchar.begin(),vecchar.end());
vector <char> vecc;
for(int i=0;i<vecchar.size();i++)
{
char ch=(char) vecchar[i];
vecc.push_back(ch);
}
for(int i=0;i<vecchar.size();i++)
{
cout<<vecc[i];
if(i<vecchar.size()-1)
{
cout<<" ";
}
}
}}//
int main()
{
int M, N;
cin >> M >> N;
int a[1000];
double b[1000];
char c[1000] = {};
for (int i = 0; i < M; i++)
{
cin >> a[i];
}
for (int i = 0; i < N; i++)
{
cin >> b[i];
}
cin >> c;
oddFilter(a, M);
oddFilter(b, N);
int len=strlen(c);
oddFilter(c,len);
}
#include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<cstring>
#include <limits>
using namespace std;
void OddFilter( int a[], int size) {
vector<int>intans;
for (int i = 0; i < size; i++) {
if (a[i] % 2 != 0) { intans.push_back(a[i]); }
}if (intans.size()==0) { cout << "No Odd!"; return; }
sort(intans.begin(), intans.end());
for (int j = 0; j < intans.size(); j++) {
cout << intans[j];
if (j != intans.size() - 1) { cout << ' '; }
}
cout << endl;
}
void OddFilter(double b[], int size) {
vector<int>doubleans;
for (int i = 0; i < size; i++) {
int tem = round(b[i]);
if (tem % 2 != 0) { doubleans.push_back(tem); }
}if (doubleans.size() == 0) { cout << "No Odd!"; return; }
sort(doubleans.begin(), doubleans.end());
for (int j = 0; j < doubleans.size(); j++) {
cout << doubleans[j];
if (j != doubleans.size() - 1) { cout << ' '; }
}
cout << endl;
}
void OddFilter(char a[], int size) {
int ascii[128];
for (int i = 0; i < 128; i++) { ascii[i] = i; }
vector<int>ansint;
int j = 0;
while (j<size) {
int tem = (int)a[j];
ansint.push_back(tem);
j++;
}
vector<int>last;
for (int z = 0; z < 128; z++) {
int count = 0;
for (int i = 0; i < ansint.size(); i++) {
if (ascii[z] == ansint[i]) {
count++;
}
}
if (count % 2 != 0) {
last.push_back(ascii[z]);
}
}if (last.size() == 0) { cout << "No Odd!"; return; }
for (int q = 0; q < last.size(); q++) {
char temporary = (char)last[q];
cout << temporary; if (q != last.size()-1) { cout << ' '; }
}
}
int main() {
int intsize, doublesize, charsize;
cin >> intsize >> doublesize;
int a[1000];
double b[1000];
char c[1000];
for (int i = 0; i < intsize; i++) { cin >> a[i]; }
for (int j = 0; j < doublesize; j++) { cin >> b[j]; }
cin.ignore();
cin.getline(c, 1000);
OddFilter(a, intsize);
OddFilter(b, doublesize);
int count=0;
int z = 0;
while (c[z] != '\0') { count++; z++; }
OddFilter(c, count);
}
7 5
6 19 5 7 32 54 3
3.4 3.5 7.8 2.0 13.1
Thisisateststring
加密
注意:题干无说明时,整数数组可能包含负数
#include<iostream>
using namespace std;
int fun(int t)
{
while(t>90)
{
t-=26;
}
while(t<65)
{
t+=26;
}
return t;
}
int main()
{
char a[10][10];
int b[10][10];
int m,n;
cin>>m>>n;
int tran[10][10]={0};
int transm[10][10]={0};
//定义
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>a[i][j];
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>b[i][j];
}
}
//输入
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
tran[i][j]=(int)a[i][j];
}
}
//字符转整数
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
transm[i][j]=tran[i][j]+b[i][j];
transm[i][j]=fun(transm[i][j]);
}
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cout<<(char) transm[i][j];
if(j<n-1)
{
cout<<" ";
}
}
if(i<m-1)
{
cout<<endl;
}
}
}
注意char类型有范围,当密文足够大时会溢出,所以用ASCII码值进行计算防止出现加密后大于128的情况
#include<iostream>
using namespace std;
int main() {
int m, n;
cin >> m >> n;
char** C = new char*[m];
for (int i = 0; i < m; i++) {
C[i] = new char[n];
}
int** K = new int* [m];
for (int i = 0; i < m; i++) {
K[i] = new int[n];
}
int** M = new int* [m];
for (int i = 0; i < m; i++) {
M[i] = new int[n];
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> C[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> K[i][j];
}
}
//M=C+K M密文 C明文 K密钥
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
int res = (int)C[i][j];
M[i][j] = res + K[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
while (M[i][j] > 90 || M[i][j] < 65) {
if (M[i][j] > 90) { M[i][j] -= 26; }
else if (M[i][j] < 65) { M[i][j] += 26; }
}
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
char res = (char)M[i][j];
cout << res;
if (j != n-1) { cout << " "; }
}if (i != m-1) { cout << endl; }
}
}
判断连续整数并反转
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main() {
string str;
cin >> str;
for(int i = 0; i < str.length(); i++) {
if(isdigit(str[i])) {
int j = i;
while(j < str.length() && isdigit(str[j]))
{
j++;
}//isdigit:判定是否为整数
int left = i, right = j - 1;
while(left < right) {
swap(str[left], str[right]);//swap:交换
left++;
right--;
}
i = j - 1;
//退回到连续整数的最后一项,最后i++开启下一个循环时从连续整数之后的第一个字符开始
}
}
字母表
#include<iostream>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
char** test = new char* [n];
for (int i = 0; i < n; i++) {
test[i] = new char[m];
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> test[i][j];
}
}
//n是行m是列
int count = 0;
if (n >= 6) {
for (int i = 0; i < m; i++) {
for (int j = 0; j <= n-6; j++) {
if ((test[j][i] == 'n' || test[j][i] == 'N') && (test[j + 1][i] == 'a' || test[j + 1][i] == 'A') && (test[j + 2][i] == 'n' || test[j + 2][i] == 'N') && (test[j + 3][i] == 'k' || test[j + 3][i] == 'K') && (test[j + 4][i] == 'a' || test[j + 4][i] == 'A') && (test[j + 5][i] == 'i' || test[j + 5][i] == 'I'))
count++;
}
}
}
if (m >= 6) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= m - 6; j++) {
if ((test[i][j] == 'n' || test[i][j] == 'N') && (test[i][j+1] == 'a' || test[i][j+1] == 'A') && (test[i][j+2] == 'n' || test[i][j+2] == 'N') && (test[i][j+3] == 'k' || test[i][j+3] == 'K') && (test[i][j+4] == 'a' || test[i][j+4] == 'A') && (test[i][j+5] == 'i' || test[i][j+5] == 'I'))
{
count++;
}
}
}
}
cout << count << endl;;
}
结尾有endl;
NKU_WLAN
cout<<0.00<<endl;输出的是0
前面的检测点不过后面的不给检测
#include<iostream>
#include<cmath>
using namespace std;
struct location {
double x, y, r;
};//储存每个信号源的数据
int main() {
int n;
double x, y;
cin >> n >> x >> y;
location* test = new location[n];
double* distance = new double[n];//储存每个信号源距alice的距离
for (int i = 0; i < n; i++) { cin >> test[i].x >> test[i].y >> test[i].r; }
for (int i = 0; i < n; i++) {
distance[i] = sqrt((x - test[i].x) * (x - test[i].x) + (y - test[i].y) * (y - test[i].y));
if (distance[i] <= test[i].r) { cout << "0.00" ; return 0; }
//判断Alice是否在信号覆盖范围内
}
double min = distance[0] - test[0].r;
for (int i = 1; i < n; i++) {
distance[i] -= test[i].r;//进入信号源的距离
if (min > distance[i]) {
min = distance[i];
}
}
cout.setf(ios::fixed);
cout.precision(2);
cout << min ;
return 0;
}
字符串指针
#include <iostream>
#include <cstring> // 仅用于strlen获取字符串长度(或用指针遍历替代)
using namespace std;
int main() {
char str1[101], str2[101];
// 输入两个字符串(空格分隔)
cin >> str1 >> str2;
// 指针初始化:p1指向str1的当前起始位置,p2指向str2的当前字符
char* p1 = str1;
char* p2 = str2;
// 记录匹配成功时str1的起始指针
char* match_pos = nullptr;
// 遍历str1的每个可能起始位置
while (p1 != '\0') {
// 临时指针:p指向当前str1起始位置,q指向str2起始位置
char p = p1;
char* q = str2;
// 逐字符匹配
while (*q != '\0' && *p == *q) {
p++;
q++;
}
// 若q遍历到str2末尾,说明匹配成功
if (*q == '\0') {
match_pos = p1;
break;
}
// 否则,p1后移一位,尝试下一个起始位置
p1++;
}
// 输出结果
if (match_pos != nullptr) {
// 输出str1中match_pos之前的字符(从str1起始到match_pos前)
char* start = str1;
while (start != match_pos) {
cout << *start;
start++;
}
cout << endl;
}
else {
cout << "Not found" << endl;
}
return 0;
}
子串重复次数
#include <iostream>
#include <string>
using namespace std;
int main() {
string str = "abcdefgabcgi";
string sub = "abc";
int count = 0;
for (int i = 0; i <= str.length() - sub.length(); i++) {
bool found = true;
for (int j = 0; j < sub.length(); j++) {
if (str[i + j] != sub[j]) {
found = false;
break;
}
}
if (found) {
count++;
}
}
cout << "String: " << str << endl;
cout << "Substring '" << sub << "' appears " << count << " times" << endl;
return 0;
}
最长重复子串
后缀法
题目描述
给你一个字符串(长度<=1000),输出字符串中最长重复子串的长度。
输入
一行,一个字符串
输出
一个整数
样例输入
abbccccd
样例输出
4
连续重复且为单个字符
#include <iostream>
#include<vector>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
string str;
cin>>str;
int nojudge=0;
if(str.size()<2)
{
nojudge=1;
}
vector <string> strback;
for(int i=0;i<str.size();i++)
{
strback.push_back(str.substr(i));
}
int maxlen=0;
string longest=" ";
sort(strback.begin(),strback.end());
for(int i=0;i<str.size()-1;i++)
{
int len=0;
while(strback[i][len]==strback[i+1][len]&&len<=strback[i].size()&&len<=strback[i+1].size())
{
len++;
}
if(len>maxlen)
{
maxlen=len;
longest=strback[i].substr(0,len);
}
}
if(nojudge==1)
{
cout<<"none"<<endl;
}
else{
cout<<maxlen<<" "<<longest;
}
}
字符串比较:直接str1==str2
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
string str;
cin >> str;
vector<int>vec;
int count = 1;
for (int i = 0; i < str.size(); i++) {
if (str[i] == str[i + 1]) { count++; }
else { vec.push_back(count); count = 1; }
}
if (vec.size() == 0) { cout << 1; return 0; }
else {
sort(vec.begin(), vec.end(), [](int a, int b) {return a > b; });
cout << vec[0];
return 0;
}
}
提取长整数的各位数字
#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main()
{
string a, b;
cin >> a;
cin >> b;
vector <int> veca;
vector <int> vecb;
for (int i = a.size()-1; i >=0 ; i--)
{
veca.push_back((int) a[i]-48);
}
for (int i = b.size()-1;i>=0; i--)
{
vecb.push_back((int) b[i]-48);
}
字符 ‘1’ ——49(ASCII)
重复字符删除
题目描述
在已升序排列的数组中(数组的元素个数为n),删除一些重复出现的元素,使得每个数字出现的次数最多为两次。
输入
第一行一个整数,n(n≥0),代表数组元素的个数
第二行n个整数,用空格分开,分别是数组中已升序排列的元素
输出
去除重复元素后的数组,每个元素间用一个空格分隔开,最后一个元素之后没有空格。
样例输入
6
0 1 1 1 2 2
样例输出
0 1 1 2 2
//有点懒
上台阶
题目描述
楼梯有n阶台阶,上楼可以一步上2阶,也可以一步上3阶,编一程序计算共有多少种不同的走法
输入
台阶总数n∈[2,60]。
输出
共有多少种走法,如果输入超出题目要求中的范围,则输出”OUT”。
样例输入
3
5
60
样例输出
2
3
#include <iostream>
using namespace std;
// 递归函数:计算走到第n阶的走法数
long long climb_stairs(int n) {
if (n == 2) {
return 1;
}
else if (n == 1) {
return 1;
}
else if (n == 0) {
return 1;
}
// 递推公式:f(n) = f(n-2) + f(n-3)
return climb_stairs(n - 2) + climb_stairs(n - 3);
}
int main() {
int n;
cin >> n;
if (n < 2 || n > 60) {
cout << "OUT" << endl;
}
else {
cout << climb_stairs(n) << endl;
}
return 0;
}
反向思维,下台阶。
P5739 阶乘
#include<iostream>
#include<string>
using namespace std;
int jiecheng(int n) {
if (n == 1) { return 1; }
else { return n * jiecheng(n - 1); }
}
int main() {
int n;
cin >> n;
cout << jiecheng(n);
}
P2388 阶乘之零
#include<iostream>
#include<string>
long yinshu5(int n) {
long count = 0;
while (n > 0) {
count += n / 5;
n /=5;
}
return count;
}
using namespace std;
int main() {
int n;
cin >> n;
long long count = 0;
for (int i = 1; i <= n; i++) {
count += yinshu5(i);
}
cout << count;
}
B2113 输出亲朋字符串
亲朋字符串定义如下:给定字符串 s 的第一个字符的 ASCII 值加第二个字符的 ASCII 值,得到第一个亲朋字符;s 的第二个字符加第三个字符得到第二个亲朋字符;依此类推。注意:亲朋字符串的最后一个字符由 s 的最后一个字符 ASCII 值加 s 的第一个字符的 ASCII 值。
输入一行,一个长度大于等于 2,小于等于 100 的字符串。
#include<iostream>
#include<string>
#include<cstring>
using namespace std;
int main() {
char str[100];
cin >> str;
char res[100];
int count = 0;
for (int i = 0; i < strlen(str)-1; i++) {
res[count++] = str[i] + str[i + 1];
}
res[count] = str[strlen(str) - 1] + str[0];
res[count+1] = '\0';
for (int i = 0; i < strlen(res); i++) {
cout << res[i];
}
}
B2143 进制转换
#include<iostream>
#include<vector>
#include<cstdlib>
using namespace std;
int main() {
vector<char>vec;
int x, m;
cin >> x >> m;
while (x > 0) {
int temp = x % m;
char res;
if (temp == 10) {
res = 'A';
}
else if (temp == 11) {
res = 'B';
}
else if (temp == 12) {
res = 'C';
}
else if (temp == 13) {
res = 'D';
}
else if (temp == 14) {
res = 'E';
}
else if (temp == 15) {
res = 'F';
}
else { res = '0' + temp; }
vec.push_back(res);
x /= m;
}
for (int i = vec.size()-1; i >=0 ; i--) { cout << vec[i]; }
system("pause");
return 0;
}
#include<iostream>
#include<string>
using namespace std;
string c = "0123456789ABCDEF";//对应字符。
//将输入的十进制整数 x 转换为 m 进制数并在控制台输出对应的字符形式。
void f(int x, int m) {
if (x / m) f(x / m, m);
//每次把数拆成 “商” 和 “余数”,先递归处理商(求高位),
// 再输出余数(当前位),实现 m 进制的逆序输出。
cout << c[x % m];//倒序输出。
}
int main() {
int x, m;
cin >> x >> m;//输入。
f(x, m);//递归。
return 0;
}
P2670 扫雷游戏
#include<iostream>
using namespace std;
int dx[8] = { 0, 0, 1, 1, 1, -1, -1, -1 }, dy[8] = { -1, 1, -1, 0, 1, -1, 0, 1 }, n, m, ans = 0;
char mp[101][101];//储存地雷信息
int main() {
cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++)
cin >> mp[i][j];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (mp[i][j] == '') cout << '';
else {
for (int k = 0; k < 8; k++) {
int x = i + dx[k], y = j + dy[k];
if (x >= 1 && x <= n && y >= 1 && y <= m && mp[x][y] == '*') ans++;
}
cout << ans;
ans = 0;
}
}
cout << endl;
}
return 0;
}
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<vector<char>>test(n, vector<char>(m));
vector<vector<char>>result(n, vector<char>(m, '0'));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> test[i][j];
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (test[i][j] == '') {
result[i][j] = '';
continue;
}
if (i - 1 >= 0) {
if (test[i - 1][j] == '*') {
result[i][j]++;
}
}
if ((i - 1 >= 0) && (j - 1 >= 0)) {
if (test[i - 1][j - 1] == '*') {
result[i][j]++;
}
}
if ((i - 1 >= 0) && (j + 1 <= m - 1)) {
if (test[i - 1][j + 1] == '*') {
result[i][j]++;
}
}
if ((j - 1 >= 0)) {
if (test[i][j - 1] == '*') {
result[i][j]++;
}
}
if ((j + 1 <= m - 1)) {
if (test[i][j + 1] == '*') {
result[i][j]++;
}
}
if ((i + 1 <= n - 1)) {
if (test[i + 1][j] == '*') {
result[i][j]++;
}
}
if ((i + 1 <= n - 1) && (j - 1 >= 0)) {
if (test[i + 1][j - 1] == '*') {
result[i][j]++;
}
}
if ((i + 1 <= n - 1) && (j + 1 <= m - 1)) {
if (test[i + 1][j + 1] == '*') {
result[i][j]++;
}
}
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cout << result[i][j];
}
cout << endl;
}
return 0;
}
P3156 查询学号
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
vector<int>idex(n);
vector<int>result(m);
for (int i = 0; i < n; i++) {
cin >> idex[i];
}
for (int i = 0; i < m; i++) {
cin >> result[i];
}
for (int i = 0; i < m; i++) {
cout << idex[result[i]-1] << endl;
}
}
P5461 赦免战俘
#include<iostream>
#include<vector>
using namespace std;
int test[1024][1024] = { 0 }, s = 1, n;
int main() {
cin >> n;
test[0][0] = 1;
for (int i = 0; i < n; i++, s *= 2) {
for (int j = 0; j < s; j++) {
for (int k = 0; k < s; k++) {
test[j + s][k] = test[j][k + s] = test[j][k];
}
}
}
for (int i = s - 1; i >= 0; i--)//倒序输出
{
for (int j = s - 1; j >= 0; j--)
cout << test[i][j] << ' ';
cout << endl;
}
}
文字游戏
//有点懒
汉诺塔
【例5.23】古印度的著名智力测验问题:有三个立柱A、B、C,在A柱上穿有大小不等的圆盘64个,较大的圆盘在下,较小者在上。要求借助于B柱将A柱上的64个圆盘移到C柱,规则为:
(1) 每次只能把一个柱上最上面的圆盘移至另一个柱的最上面;
(2) 每个柱上总保持较大的圆盘在下,较小者在上。
编制程序, 实现将任意n个圆盘从A柱借助于B柱移到C柱, 并显示出全部移动过程
#include<iostream>
using namespace std;
void move(char source, char target) // 定义无返回值函数move,接收两个char参数:源柱、目标柱
{
cout << source << "=>" << target << endl; // 输出移动步骤(比如"A=>C",表示盘子从A移到C)
}
void hanoi(int n, char source, char temp, char target) {
// n=n的核心含义是 “当前递归层需要处理的盘子数量”
// —— 更具体地说,是 “需要从source柱移动到target柱的盘子总数
// source=源柱,temp=中转柱,target=目标柱
// 注意这些都是形参,并不是说这三根柱子固定
//hanoi函数的作用就是把n个盘子借助第二个参数的柱子从第一个参数的柱子移动到第三个参数的柱子
if (n == 1) //递归终止条件:只有1个盘子时
move(source, target); // 直接调用move,把这个盘子从源柱移到目标柱
else { // 递归条件:盘子数>1时
// 将n-1个盘子从一柱,以三柱为中转,移到二柱
hanoi(n - 1, source, target, temp);
// 关键1:拆解子问题1——先挪走上面n-1个盘子到二柱
// 将最下面的第n个盘子从一柱直接移到三柱
move(source, target); // 8. 关键2:移动最底层的大盘子到目标柱
// 将n-1个盘子从中转柱,以源柱为中转,移到目标柱
hanoi(n - 1, temp, source, target);
// 9. 关键3:拆解子问题2——把n-1个盘子从中转柱挪到目标柱
}
}
int main() {
int n;
cout << "输入盘子数:" << endl;
cin >> n;
hanoi(n, 'A', 'B', 'C');
return 0;
}
25.1简单计算
我们是考的是这一套题,答案大家自己尝试一下吧
25.2两点间距离
此题学无止境学长表示他当时定义了一个distance结构体,结果distance是系统函数,然后找了半天都找不到问题(呜呜呜)
25.3内存分配
#include <iostream>
#include <vector>
#include <string>
using namespace std;
int main() {
int size, n;
// 读取内存大小
if (!(cin >> size)) return 0;
// 读取操作次数
if (!(cin >> n)) return 0;
// 初始化内存,0 表示空闲,1 表示已分配
vector<int> memory(size, 0);
for (int i = 0; i < n; ++i) {
string op;
cin >> op;
if (op == "ALLOCATE") {
int request_size;
cin >> request_size;
int found_idx = -1;
// 遍历内存寻找第一个足够大的连续空闲块
for (int j = 0; j <= size - request_size; ++j) {
bool can_allocate = true;
for (int k = j; k < j + request_size; ++k) {
if (memory[k] == 1) {
can_allocate = false;
break;
}
}
if (can_allocate) {
found_idx = j;
break;
}
}
if (found_idx != -1) {
// 标记为已分配
for (int j = found_idx; j < found_idx + request_size; ++j) {
memory[j] = 1;
}
cout << "Allocate at index " << found_idx << endl;
}
else {
cout << "Allocation failed" << endl;
}
}
else if (op == "FREE") {
int start, length;
cin >> start >> length;
bool is_valid = true;
// 1. 检查越界 (索引小于0或超出数组范围)
if (start < 0 || length <= 0 || start + length > size) {
is_valid = false;
}
else {
// 2. 检查释放的内存块是否包含未分配(已经是0)的部分
for (int j = start; j < start + length; ++j) {
if (memory[j] == 0) {
is_valid = false;
break;
}
}
}
if (is_valid) {
// 执行释放,置为0
for (int j = start; j < start + length; ++j) {
memory[j] = 0;
}
cout << "Free " << length << " blocks from index " << start << endl;
}
else {
cout << "Invalid free operation" << endl;
}
}
}
return 0;
}
学无止境:鄙人代码(考完做的)
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
int size;//内存大小
cin >> size;
int n;//操作次数
cin >> n;
int* restore = new int[size] {0};//模拟的内存数组
for (int q = 0; q < n; q++) {
string rule;
cin >> rule;
if (rule == "ALLOCATE") {
int request_size;
cin >> request_size;
if (request_size > size) {
cout << "Allocation failed" << endl;
continue;
}
bool success = true;
int i = 0;
for (i; i <= size - request_size; i++) {
success = true;
for (int j = i; j < i + request_size; j++)
{
if (restore[j] == 0) {
continue;
}
else {
success = false;
break;
}
}
if (success == true) {
cout << "Allocate at index " << i << endl;
for (int z = i; z < i + request_size; z++) {
restore[z] = 1;
}
break;
}
}
if ((i == size - request_size + 1) && success == false) {
cout << "Allocation failed" << endl;
}
}
else if (rule == "FREE") {
int start, length;
cin >> start >> length;
if (start < 0 || length < 0 || start + length > size) {
cout << "invalid free operation" << endl;
}
bool check = true;
for (int i = start; i < start + length; i++) {
if (restore[i] == 0) {
check = false;
cout << "invalid free operation" << endl;
break;
}
}
if (check == true) {
for (int i = start; i < start + length; i++) {
restore[i] = 0;
}
cout << "Free " << length << " blocks from index " << start << endl;
}
}
}
delete[] restore;
return 0;
}
24.1进制转换
'\0'!='0'
'\0'=0 空字符
'0'=48 数字0
将输出直接在第二个函数中完成,因为是赋值传参,又无返回值
#include<iostream>
using namespace std;
int radix(char octstring[], int len);
void radix(int& n);
int main() {
int m;
cin >> m;
for (int i = 1; i <= m; i++) {
char c;
cin >> c;
if (c != 'O' && c != 'o' && c != 'D' && c != 'd') {
cout << "Wrong input" << endl;
return 0;
}
if (c == 'o' || c == 'O') {
char test[7];
cin >> test;
int res = radix(test, 7);
cout << res << endl;
}
else if (c == 'd' || c == 'D') {
int test;
cin >> test;
radix(test);
cout << test;
}
}
}
int radix(char octstring[], int len) {
int res=0;
for (int i =0 ; i <strlen(octstring) ; i++) {
int tem = octstring[i] - '0';
for (int j = 0; j < strlen(octstring)-i-1; j++) {
tem *= 8;
}
res += tem;
}
return res;
}
void radix(int& n) {
int tem = n;
n = 0;
int temparr[10];
int i = 0;
while (tem >0) {
temparr[i] = tem % 8;
tem = (tem - temparr[i]) / 8;
i++;
}
for (int j = i - 1; j >= 0; j--) {
n = temparr[j] + n * 10;
}
}
#include <iostream>
#include <cstring>
using namespace std;
// 重载函数1:八进制字符串转十进制整数(按权展开法)
int radixConvert(char octString[], int len) {
int decimal = 0;
for (int i = 0; i < len; i++) {
int digit = octString[i] - '0'; // 字符转数字
int weight = 1;//计算权重
for (int j = 0; j < len - 1 - i; j++) {
weight *= 8;
}
decimal += digit * weight;
}
return decimal;
}
// 重载函数2:十进制整数转八进制字符串(取余法)
void radixConvert(int n) {
char oct[7] = { 0 };
int index = 0;
if (n == 0) {
cout << "0";
return;
}
// 取余法:除8取余,逆序存储
while (n > 0) {
int remainder = n % 8;
oct[index++] = remainder + '0'; // 数字转字符
n = n / 8;
}
// 逆序输出(因为取余结果是倒序的)
for (int i = index - 1; i >= 0; i--) {
cout << oct[i];
}
}
int main() {
int M;
cin >> M;
if (M <= 0 || M >= 6) { // 题目要求0<M<6
cout << "Wrong input" << endl;
return 0;
}
for (int i = 0; i < M; i++) {
char c;
char data[7]; // 八进制最长6位,十进制最长65535(5位)
cin >> c >> data;
if (c == 'O' || c == 'o') {
// 八进制字符串转十进制
int len = strlen(data);
if (len > 6) { // 题目限制八进制字符串最长6位
cout << "Wrong input" << endl;
return 0;
}
// 验证八进制字符是否合法(只能是0-7)
for (int j = 0; j < len; j++) {
if (data[j] < '0' || data[j] > '7') {
cout << "Wrong input" << endl;
return 0;
}
}
int decimal = radixConvert(data, len);
cout << decimal << endl;
}
else if (c == 'D' || c == 'd') {
// 十进制数字转八进制
int num = atoi(data); // 字符串转整数
if (num < 0 || num > 65535) { // 题目限制非负且不超过65535
cout << "Wrong input" << endl;
return 0;
}
radixConvert(num);
cout << endl;
}
else {
// 其他字符,输入错误
cout << "Wrong input" << endl;
return 0;
}
}
return 0;
}
#include <iostream>
#include <cstring>
using namespace std;
// 重载函数1:八进制字符串转十进制整数(按权展开法)
int radixConvert(char test[], int len) {
int res=0;
for (int i = 0; i<len; i++) {
int num = 0;
num = test[i] - '0';
int weight=1;
for (int j = 1; j <= len - i - 1; j++) { weight*=8; }
res += num * weight;
}
cout << res << endl;
return 0;
}
void radixConvert(int n) {
char test[8] = { 0 };
int count = 0;
while (n > 0) {
test[count++] = n % 8+'0';
n /= 8;
}
for (int i = count - 1; i >=0; i--) {
cout << test[i];
}
cout << endl;
}
int main() {
int m;
cin >> m;
for (int i = 0; i < m; i++) {
char c;
cin >> c;
if (c != 'd' && c != 'D' && c != 'o' && c != 'O') {
cout << "Wrong input" << endl;
return 0;
}
if (c == 'd' || c == 'D') {
int test;
cin >> test;
radixConvert(test);
}
if (c == 'o' || c == 'O') {
char test[7] = { '0'};
cin >> test;
int len=0;
for (int j = 0; test[j] != '\0'; j++) {
len = j+1;
}
radixConvert(test, len);
}
}
}
24.2职员信息统计
样例:
6
0000000001 David M D 2400 4000
0000000002 Lucy F C 3600 1200
0000000003 Leo M A 5500 1500
0000000004 Jenny F A 4500 2000
0000000005 Don M B 4000 1400
0000000006 Sunny F B 3000 2500
工号用string类型可以直接比较
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
struct emp {
string num;
string name;
char gender;
char grade;
int salary;
int fsalart;
};
int main(){
int n;
cin >> n;
vector <emp>tememployer(n);
for (int i = 0; i < n; i++) {
cin >> tememployer[i].num >> tememployer[i].name >> tememployer[i].gender >> tememployer[i].grade >> tememployer[i].salary >> tememployer[i].fsalart;
}
vector<emp>employer;
for (int i = 0; i < n; i++) {
if (tememployer[i].grade != 'D') {
employer.push_back(tememployer[i]);
}
}
sort(employer.begin(), employer.end(), [](emp a, emp b) {
if ((a.salary + a.fsalart) != (b.salary+ b.fsalart))
{
return (a.salary + a.fsalart) > (b.salary + b.fsalart);
}
else if ((a.salary + a.fsalart) != (b.salary + b.fsalart)) {
return a.num > b.num;
}
});
for (int i = 0; i < employer.size(); i++) {
int sum = employer[i].salary + employer[i].fsalart;
cout << employer[i].num << " " << employer[i].name << " " << employer[i].gender << " " << sum << endl;
}
}
#include<iostream>
#include<vector>
using namespace std;
struct str{
string index;
string names;
char gender;
char grade;
int fousalary;
int flsalary;
int totalsalary;
};
int main()
{
int n;
cin>>n;
vector <str> vec;
for(int i=0;i<n;i++)
{
str t;
cin>>t.index>>t.names>>t.gender>>t.grade>>t.fousalary>>t.flsalary;
t.totalsalary=t.fousalary+t.flsalary;
vec.push_back(t);
}
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(vec[i].totalsalary<vec[j].totalsalary)
{
str tran;
tran=vec[i];
vec[i]=vec[j];
vec[j]=tran;
}
}
}
for(int i=0;i<n;i++)
{
if(vec[i].grade=='D')
{
continue;
}
else{
cout<<vec[i].index<<" "<<vec[i].names<<" "<<vec[i].gender<<" "<<vec[i].totalsalary;
if(i<n-1)
{
cout<<endl;
}
}
}
}
24.3黑白格子
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
if (n < 4 || m < 4) {
cout << "No" << endl;
return 0;
}
vector<vector<int>>vec(n, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
cin >> vec[i][j];
}
}
for (int r = 0; r <= n - 4; r++) {
for (int c = 0; c <= m - 4; c++) {
if (vec[r][c] == 1 && vec[r][c + 1] == 1 && vec[r][c + 2] == 1 && vec[r][c + 3] == 1 && vec[r + 1][c] == 1 && vec[r + 1][c + 1] == 0 && vec[r + 1][c + 2] == 0 && vec[r + 1][c + 3] == 1 && vec[r + 2][c] == 1 && vec[r + 2][c + 1] == 0 && vec[r + 2][c + 2] == 0 && vec[r + 2][c + 3] == 1 && vec[r + 3][c] == 1 && vec[r + 3][c + 1] == 1 && vec[r + 3][c + 2] == 1 && vec[r + 3][c + 3] == 1)
{
cout << "Yes" << endl;
return 0;
}
}
}
cout << "No" << endl;
return 0;
}
#include<iostream>
#include<vector>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
vector <vector <int>> a(n,vector <int> (m));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>a[i][j];
}
}
int judge1=0;
int judge2=0;
if(m<4||n<4)
{
cout<<"No";
return 0;
}
else{
for(int i=0;i<=n-4;i++)
{
for(int j=0;j<=n-4;j++)
{
if(a[i][j]==1&&a[i][j+1]==1&&a[i][j+2]==1&&a[i][j+3]==1
&&a[i+1][j]==1&&a[i+1][j+3]==1&&a[i+1][j+1]==0&&a[i+1][j+2]==0
&&a[i+2][j]==1&&a[i+2][j+3]==1&&a[i+2][j+1]==0&&a[i+2][j+2]==0
&&a[i+3][j]==1&&a[i+3][j+1]==1&&a[i+3][j+2]==1&&a[i+3][j+3]==1)
{
judge1=1;
}
if(judge1==1)
{
judge2=1;
break;
}
}
if(judge2==1)
{
cout<<"Yes";
break;
}
}
}
}
23.1基本运算
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main() {
vector<int>vec(10);
for (int i = 0; i < 10; i++) {
cin >> vec[i];
}
int sum = 0, max = vec[0], min = vec[0];
for (int i = 0; i < 10; i++) {
sum += vec[i];
if (min > vec[i]) {
min = vec[i];
}
if (max < vec[i]) {
max = vec[i];
}
}
string str;
cin >> str;
for (int i = 0; i < str.size(); i++) {
if (str[i] >= 'a' && str[i] <= 'z') {
str[i] = str[i] - 32;
}
}
cout << min << " " << max << " " << sum << " " << endl<<str << endl;;
return 0;
}
23.2矩阵运算
样例
3
1 2 3
4 5 6
7 8 9
2 3 4
5 6 7
8 9 10
#include<iostream>
#include<vector>
bool isprime(int n) {
if (n <= 1) { return false; }
for (int i = 2; i * i <= n; i++) {
if (n % i == 0) { return false; }
}
return true;
}
using namespace std;
int main() {
int m;
cin >> m;
vector<vector<int>>a(m, vector<int>(m));
vector<vector<int>>b(m, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
cin >> a[i][j];
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
cin >> b[i][j];
}
}
vector<vector<int>>a1 = a;
vector<vector<int>>b1 = b;
vector<vector<int>>c1(m, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (!isprime(a1[i][j])) { a1[i][j] += 1; }
if (!isprime(b1[i][j])) { b1[i][j] += 1; }
c1[i][j] = a1[i][j] + b1[i][j];
cout << c1[i][j] ;
if (j != m - 1) { cout << " "; }
}
cout << endl;
}
vector<vector<int>>a2 = a;
vector<vector<int>>b2 = b;
vector<vector<int>>c2(m, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (a2[i][j] % 2 == 0) { a2[i][j] -= 1; }
if (b2[i][j] % 2 == 0) { b2[i][j] -= 1; }
c2[i][j] = a2[i][j] - b2[i][j];
cout << c2[i][j] ;
if (j != m - 1) { cout << " "; }
}
cout << endl;
}
vector<vector<int>>a3 = a;
vector<vector<int>>b3 = b;
vector<vector<int>>c3(m, vector<int>(m));
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
if (a3[i][j] % 2 != 0) { a3[i][j] *= 2; }
if (b3[i][j] % 2 != 0) { b3[i][j] *= 2; }
}
}
for (int i = 0; i < m; i++) {
for (int j = 0; j < m; j++) {
c3[i][j] = 0;
for (int z = 0; z < m; z++) {
c3[i][j] += a3[i][z] * b3[z][j];
}
cout << c3[i][j] ;
if (j != m - 1) { cout << " "; }
}
cout << endl;
return 0;
}
}
23.3函数
#include<iostream>
#include<vector>
using namespace std;
void trans10to16(int a) {
int res=0;
vector<char>yushu;
while (a > 0) {
char charr;
int tem = a % 16;
if (tem > 9) { charr = tem - 10 + 'a'; }
else if (tem < 10) { charr = tem + '0'; }
yushu.push_back(charr);
a /= 16;
}if (yushu.size() < 2) {
for (int i = 0; i < 2 - yushu.size(); i++)
cout << '0';
}
for (int i = yushu.size()-1; i>=0; i--) {
cout << yushu[i];
}
}
void colortrans(int r, int g, int b) {
cout << '#';
trans10to16(r);
trans10to16(g);
trans10to16(b);
}
void colortrans(long num) {
vector <char>vec;
while (num > 0) {
char charr;
int tem = num % 16;
if (tem > 9) { charr = tem - 10 + 'a'; }
else if (tem < 10) { charr = tem + '0'; }
vec.push_back(charr);
num /= 16;
}
cout << '#';
if (vec.size() < 6) {
for (int i = 0; i < 6 -vec.size(); i++)
cout << '0';
}
for (int i = vec.size() - 1; i >= 0; i--) {
cout << vec[i];
}
}
int main() {
char c;
cin >> c;
if (c != 'r' && c != 'R' && c != 'd' && c != 'D') {
cout << "Wrong input!";
return 0;
}
else if (c == 'r' || c == 'R') {
int r, g, b;
cin >> r >> g >> b;
if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255)
{
cout << "Wrong Input!";
}
colortrans(r, g, b);
}
else if (c == 'd' || c == 'D') {
long num;
cin >> num;
colortrans(num);
}
}
#include<iostream>
using namespace std;
void Color2Hex(int r, int g, int b)
{
if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255)
{
cout << "Wrong Input!";
}
else {
char a[10];
a[0] = '#';
if (r / 16 >= 10)
{
a[1] = r / 16 - 10 + 97;
}
else { a[1] = r / 16 + 48; }
if (r % 16 >= 10)
{
a[2] = r % 16 - 10 + 97;
}
else { a[2] = r % 16 + 48; }
if (g / 16 >= 10)
{
a[3] = g / 16 - 10 + 97;
}
else { a[3] = g / 16 + 48; }
if (g % 16 >= 10)
{
a[4] = g % 16 - 10 + 97;
}
else { a[4] = g % 16 + 48; }
if (b / 16 >= 10)
{
a[5] = b / 16 - 10 + 97;
}
else { a[5] = b / 16 + 48; }
if (b % 16 >= 10)
{
a[6] = b % 16 - 10 + 97;
}
else { a[6] = b % 16 + 48; }
a[7] = '\0';
cout << a;
}
}
void Color2Hex(float c, float m, float y, float k)
{
int r = (int)255.0 * (1 - c) * (1 - k);
int g = (int)255.0 * (1 - m) * (1 - k);
int b = (int)255.0 * (1 - y) * (1 - k);
if (r < 0 || r>255 || g < 0 || g>255 || b < 0 || b>255)
{
cout << "Wrong Input!";
}
else {
char a[10];
a[0] = '#';
if (r / 16 >= 10)
{
a[1] = r / 16 - 10 + 97;
}
else { a[1] = r / 16 + 48; }
if (r % 16 >= 10)
{
a[2] = r % 16 - 10 + 97;
}
else { a[2] = r % 16 + 48; }
if (g / 16 >= 10)
{
a[3] = g / 16 - 10 + 97;
}
else { a[3] = g / 16 + 48; }
if (g % 16 >= 10)
{
a[4] = g % 16 - 10 + 97;
}
else { a[4] = g % 16 + 48; }
if (b / 16 >= 10)
{
a[5] = b / 16 - 10 + 97;
}
else { a[5] = b / 16 + 48; }
if (b % 16 >= 10)
{
a[6] = b % 16 - 10 + 97;
}
else { a[6] = b % 16 + 48; }
a[7] = '\0';
cout << a;
}
}
int main()
{
int a[3];
float d[4];
char w;
cin >> w;
if (w == 'c' || w == 'C')
{
for (int i = 0; i < 4; i++)
{
cin >> d[i];
}
Color2Hex(d[0], d[1], d[2], d[3]);
}
if (w == 'r' || w == 'R')
{
for (int i = 0; i < 3; i++)
{
cin >> a[i];
}
Color2Hex(a[0], a[1], a[2]);
}
if (!(w == 'c' || w == 'C') && !(w == 'r' || w == 'R'))
{
cout << "Wrong Input!";
}
}
#include<iostream>
#include<vector>
#include<string>
using namespace std;
string trans(int tr)
{
vector <int> vec;
if(tr==0)
{
return "00";
}
else{
while(tr>0)
{
int t;
t=tr%16;
vec.push_back(t);
tr=tr/16;
}
string result;
for(int i=vec.size()-1;i>=0;i--)
{
if(vec[i]==10){result.push_back('a');}
if(vec[i]==11){result.push_back('b');}
if(vec[i]==12){result.push_back('c');}
if(vec[i]==13){result.push_back('d');}
if(vec[i]==14){result.push_back('e');}
if(vec[i]==15){result.push_back('f');}
if(vec[i]<10){result.push_back((char) (vec[i]+'0'));}
//将整型强制转换为字符型
}
return result;
}
}
void colorhex(int r,int g,int b)
{
cout<<"#"<<trans(r)<<trans(g)<<trans(b);
}
void colorhex(long num)
{
string addn=trans(num);
string plus;
if(addn.size()<6)
{
int del=6-addn.size();
for(int i=0;i<del;i++)
{
plus.push_back('0');//插入字符,插入整数不用单引号
}
}
cout<<"#"<<plus<<addn;
}
int main()
{
char ch;
cin>>ch;
int rcolor,gcolor,bcolor;
int n;
if(ch=='r'||ch=='R')
{
cin>>rcolor>>gcolor>>bcolor;
if(rcolor<0||rcolor>255){cout<<"Wrong Input";}
if(gcolor<0||gcolor>255){cout<<"Wrong Input";}
if(bcolor<0||bcolor>255){cout<<"Wrong Input";}
}
else{
if(ch=='d'||ch=='D')
{
cin>>n;
}
else{
cout<<"Wrong Input!";
}
}
if(ch=='r'||ch=='R')
{
colorhex(rcolor,gcolor,bcolor);
}
if(ch=='d'||ch=='D')
{
colorhex(n);
}
}
23.4结构体
示例:仅验证题干的版本(int类型坐标)
#include<iostream>
#include<cmath>
using namespace std;
struct point{
int x;
int y;
};
int main()
{
point linea1,linea2,lineb1,lineb2;
point recta1,recta2,rectb1,rectb2;
cin>>linea1.x>>linea1.y>>linea2.x>>linea2.y;
cin>>lineb1.x>>lineb1.y>>lineb2.x>>lineb2.y;
cin>>recta1.x>>recta1.y>>recta2.x>>recta2.y;
cin>>rectb1.x>>rectb1.y>>rectb2.x>>rectb2.y;
if(linea1.x-linea2.x!=0&&lineb1.x-lineb2.x!=0)
{
int k1=(linea1.y-linea2.y)/(linea1.x-linea2.x);
int k2=(lineb1.y-lineb2.y)/(lineb1.x-lineb2.x);
double judge=k1*k2;
if(judge==-1)
{
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}}
else
{
if(linea1.x-linea2.x==0&&lineb1.x-lineb2.x!=0)
{
if(lineb1.y-lineb2.y==0)
{
cout<<"True"<<endl;
}
else{
cout<<"False"<<endl;
}
}
else{
if(lineb1.x-lineb2.x==0&&linea1.x-linea2.x!=0)
{
if(linea1.y-linea2.y==0)
{
cout<<"True"<<endl;
}
else{
cout<<"Fasle"<<endl;
}
}
else{
cout<<"False"<<endl;
}
}
}
int dx,dy;
int pand=0;
dx=sqrt(recta2.x-recta1.x)+sqrt(rectb2.x-rectb1.x);
dy=sqrt(recta2.y-recta1.y)+sqrt(rectb2.y-rectb1.y);
int Dx,Dy;
Dx=sqrt(rectb2.x>recta2.x?rectb2.x:recta2.x-recta1.x<rectb1.x?recta1.x:rectb1.x);
Dy=sqrt(rectb2.y>recta2.y?rectb2.y:recta2.y-recta1.y<rectb1.y?recta1.y:rectb1.y);
if(Dy<dy&&Dx<dx)
{
pand=1;
}
int Cir;
int length,width;
if(pand==1)
{
length=sqrt(dx-Dx);
width=sqrt(dy-Dy);
Cir=2*(length+width);
cout<<Cir;
}
else{
cout<<"False";
}
}
#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
using namespace std;
struct point {
int x;
int y;
};
struct rect {
point a;
point b;
};
int main() {
point a1, a2, b1, b2;
cin >> a1.x >> a1.y >> a2.x >> a2.y >> b1.x >> b1.y >> b2.x >> b2.y;
float ka,kb;
if (((a1.x == a2.x) && (b1.y == b2.y))|| ((b1.x == b2.x) && (a1.y == a2.y))) {
cout << "True" << endl;
goto s;
}
else if((a1.x == a2.x)|| (b1.x == b2.x)){
cout<< "False" << endl;
goto s;
}
else {
ka = (a1.y - a2.y) / (a1.x - a2.x);
kb = (b1.y - b2.y) / (b1.x - b2.x);
if (ka * kb == -1) {
cout << "True" << endl;
}
else { cout << "False" << endl; }
}
s:rect c, d;
cin >> c.a.x >> c.a.y >> c.b.x >> c.b.y >> d.a.x >> d.a.y >> d.b.x >> d.b.y;
int c_left= min(c.a.x, c.b.x);
int c_right= max(c.a.x, c.b.x);
int c_up= max(c.a.y, c.b.y);
int c_down= min(c.a.y, c.b.y);
int d_left = min(d.a.x, d.b.x);
int d_right = max(d.a.x, d.b.x);
int d_up = max(d.a.y, d.b.y);
int d_down = min(d.a.y, d.b.y);
if (c_left >= d_right || c_right <= d_left || c_up <= d_down || c_down >= d_up) {
cout << "false";
}
else {
int C;
int up = min(c_up, d_up);
int down = max(c_down, d_down);
int left = max(d_left, c_left);
int right = min(d_right, c_right);
C = (up - down + right - left) * 2;
cout << C;
}
}
25.1伯苓
25.2伯苓
25.3伯苓
20.3字符串数组类
降序
5
nankaidaxue
jisuanjixueyuan
wanghaocheng
rank
first
dnnx
jjnx
hhnn
nr
frt
#include <iostream>
using namespace std;
class MyStrArr
{
private:
char **strArr; // 字符指针数组
int count; // 字符串个数
public:
// 构造函数
MyStrArr(char *arr, int n)
{
count = n;
strArr = new char[count];
for(int i = 0; i < count; i++)
{
strArr[i] = arr[i];
}
}
// 数据处理函数
void Fun()
{
for(int i = 0; i < count; i++)
{
char temp[105]; // 临时数组存放保留字符
int k = 0;
// 遍历当前字符串
for(int j = 0; strArr[i][j] != '\0'; j++)
{
// 条件:下标为偶数 且 ASCII 为偶数
if(j % 2 == 0 && ((int)strArr[i][j]) % 2 == 0)
{
temp[k++] = strArr[i][j];
}
}
temp[k] = '\0';
// 排序,冒泡排序
for(int m = 0; m < k - 1; m++)
{
for(int n = 0; n < k - 1 - m; n++)
{
if(temp[n] > temp[n+1])
{
char t = temp[n];
temp[n] = temp[n+1];
temp[n+1] = t;
}
}
}
// 复制回原字符串
int idx = 0;
while(temp[idx] != '\0')
{
strArr[i][idx] = temp[idx];
idx++;
}
strArr[i][idx] = '\0';
}
}
// 输出函数
void Output()
{
for(int i = 0; i < count; i++)
{
if(strArr[i][0] == '\0')
cout << 0 << endl;
else
cout << strArr[i] << endl;
}
}
};
int main()
{
int len;
cin >> len;
char **arr = new char*[len];
for(int i = 0; i < len; i++)
{
arr[i] = new char[105];
cin >> arr[i];
}
MyStrArr obj(arr, len);
obj.Fun();
obj.Output();
return 0;
}
17.3链表
1 1 1
1 1 2
1 1 3
2 1
2 2
2 3
3 2
2 1
2 2
2 3
1 2 4
2 4
结果:
1 1 1
1 1 2
1 1 3
2 1
3
2 2
2
2 3
1
3 2
2 1
2
2 2
-1
2 3
1
1 2 4
2 4
2
#include<iostream>
using namespace std;
struct node {
int val;
node* next;
node(int a) :next(NULL), val(a) { }
};
class list {
private:
node* head;
node* tail;
int count;
public:
list():head(NULL),tail(NULL),count(0){}
void insert(int k,int val){
if (k<1 || k>count + 1) {
return;
}
if (k > 1 && head == NULL) {
return;
}
node* newnode = new node(val);
if (k == 1) {
newnode->next = head;
head = newnode;
if (head == NULL) {
tail = newnode;
}
count++;
return;
}
if (k == count + 1) {
tail->next = newnode;
tail = newnode;
count++;
return;
}
if (k > 1 && k < count + 1) {
node* curr = head;
int pos = 1;
for (pos; pos < k - 1; pos++) {
curr = curr->next;
}
newnode->next=curr->next;
curr->next = newnode;//剪断
count++;
}
}
int find(int val){
node* curr = head;
int pos = 1;
bool iffind=false;
for (int i = 0; i < count; i++) {
if (curr->val == val) {
iffind = true;
break;
}
pos++;
curr = curr->next;
}if (iffind) { return pos; }
else { return -1; }
}
void deleted(int val){
node* curr = head;
if (curr->val == val) {
node* tem = head;
head = curr->next;
curr = curr->next;
delete tem;
count--;
}//只要curr指向的不是最后一个节点
while (curr->next != NULL) {
if (curr->next->val == val) {
node* tem = curr->next;
curr->next = curr->next->next;
delete tem;
count--;
}
curr = curr->next;
}
}
};
int main() {
list mylist;
int rule;
cin >> rule;
while (rule != 4) {
if (rule == 1) {
int x, y;
cin >> x >> y;
mylist.insert(x, y);
}
else if (rule == 2) {
int x;
cin >> x;
cout<<mylist.find(x)<<endl;
}
else if (rule == 3) {
int x;
cin >> x;
mylist.deleted(x);
}
cin >> rule;
}
}
25.1类与对象
#include<iostream>
#include<string>
using namespace std;
class person{
private:
string name;
int age;
public:
string getname(){
return name;
}
int getage(){
return age;
}
person(){}
person(string name,int age):name(name),age(age){
if(age>100||age<1){
cout<<"Person reminds to check age info!"<<endl;
}
}
virtual void showinfo(){ }
};
class student:public person{
int score;
public:
student(string name,int age,int score):person(name,age),score(score){
if(score>100||score<0){
cout<<"Student reminds to check score info!"<<endl;
}
}
void showinfo(){
cout<<"name:"<<this->getname()<<endl<<"age:"<<this->getage()<<endl<<"score:"<<this->score;
}
};
int main(){
string name;
int age;
int score;
cin>>name>>age>>score;
student mystudent(name,age,score);
mystudent.showinfo();
return 0;
}
25.2继承派生
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
using namespace std;
class product{
protected:
int id;
string name;
public:
product(int id,string name):id(id),name(name){}
virtual void showinfo()=0;
int getid(){
return id;
}
virtual int getstock()=0;
string getname(){
return name;
}
~product(){}
};
class Normalelec:public product{
double price;
int stock;
public:
Normalelec(int id,string name,double price,int stock):product(id,name),price(price),stock(stock){}
void showinfo(){
cout<<getid()<<' '<<getname()<<' '<<price<<' '<<stock<<endl;
}
int getstock(){
return stock;
}
};
class Highelec:public product{
double price;
int stock;
string level;
public:
Highelec(int id,string name,double price,int stock,string level):product(id,name),price(price),stock(stock),level(level){}
void showinfo(){
cout<<getid()<<' '<<getname()<<' '<<price<<' '<<stock<<' '<<level<<endl;
}
int getstock(){
return stock;
}
};
int main(){
string rule;
cin>>rule;
vector<product*>vec;
bool chongfu=false;
while(rule!="exit"){
if(rule=="add"){
int id;
string name;
double price;
int stock;
string level;
cin>>id>>name>>price>>stock>>level;
if(level=="exit"||level=="add"||level=="query"||level=="total"){
productp=new Normalelec(id,name,price,stock);
vec.push_back(p);
rule=level;
chongfu=true;
}else{
productp=new Highelec(id,name,price,stock,level);
vec.push_back(p);
}
}
else if(rule=="query"){
int id;
cin>>id;
bool isfind=false;
int n=vec.size();
for(int i=0;i<n;i++){
if(vec[i]->getid()==id){
vec[i]->showinfo();
isfind=true;
break;
}
}if(isfind==false)
{ cout<<"not found"<<endl;}
}
else if(rule=="total"){
int sum=0;
int n=vec.size();
for(int i=0;i<n;i++){
int tem=vec[i]->getstock();
sum+=tem;
}
cout<<sum<<endl;
}
if(chongfu){
chongfu=false;
continue;
}else{
cin>>rule;
}
}
return 0;
}
25.3链表、栈与队列综合实现
学无止境的石山代码嘿嘿(只能出此下策了)大家自己研究一下怎么解题
#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<list>
#include<stack>
#include<deque>
#include<queue>
using namespace std;
int main(){
char jiegou;
char shuju;
cin>>jiegou>>shuju;
if(jiegou=='L'){
if(shuju=='I'){
list<int>li;
int len;
cin>>len;
for(int i=0;i<len;i++){
int val;
cin>>val;
li.emplace_back(val);
}//tianjian
li.sort();
list<int>tem=li;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop_front();
}
cout<<endl;//chushixianshi
char rule;
int v;
cin>>rule>>v;
if(rule=='A'){
li.emplace_front(v);
li.sort();
len++;
list<int>tem1=li;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop_front();
}
cout<<endl;
}else if(rule=='R'){
li.remove(v);
list<int>tem2=li;
while(!tem2.empty()){
cout<<tem2.front()<<' ';
tem2.pop_front();
}
cout<<endl;
}
//diercicaozuo
int index;
cin>>index;
for(int i=0;i<index;i++){
li.pop_front();
}
cout<<li.front();
}
if(shuju=='D'){
list<double>li;
int len;
cin>>len;
for(int i=0;i<len;i++){
double val;
cin>>val;
li.emplace_back(val);
}//tianjian
li.sort();
list<double>tem=li;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop_front();
}
cout<<endl;//chushixianshi
char rule;
double v;
cin>>rule>>v;
if(rule=='A'){
li.emplace_front(v);
li.sort();
len++;
list<double>tem1=li;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop_front();
}
cout<<endl;
}else if(rule=='R'){
li.remove(v);
list<double>tem2=li;
while(!tem2.empty()){
cout<<tem2.front()<<' ';
tem2.pop_front();
}
cout<<endl;
}
//diercicaozuo
int index;
cin>>index;
for(int i=0;i<index;i++){
li.pop_front();
}
cout<<li.front();
}
if(shuju=='C'){
list<char>li;
int len;
cin>>len;
for(int i=0;i<len;i++){
char val;
cin>>val;
li.emplace_back(val);
}//tianjian
li.sort();
list<char>tem=li;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop_front();
}
cout<<endl;//chushixianshi
char rule;
char v;
cin>>rule>>v;
if(rule=='A'){
li.emplace_front(v);
li.sort();
len++;
list<char>tem1=li;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop_front();
}
cout<<endl;
}else if(rule=='R'){
li.remove(v);
list<char>tem2=li;
while(!tem2.empty()){
cout<<tem2.front()<<' ';
tem2.pop_front();
}
cout<<endl;
}
//diercicaozuo
int index;
cin>>index;
for(int i=0;i<index;i++){
li.pop_front();
}
cout<<li.front();
}
}
if(jiegou=='S'){
if(shuju=='I'){
int len;
cin>>len;
stack<int> skac;
for(int i=0;i<len;i++){
int val;
cin>>val;
skac.push(val);
}
stack<int>tem=skac;
for(int i=0;i<len;i++){
cout<<tem.top()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
int val;
cin>>val;
skac.push(val);
len++;
}else if(rule=='R'){
skac.pop();
len--;
}
stack<int>tem1=skac;
for(int i=0;i<len;i++){
cout<<tem1.top()<<' ';
tem1.pop();
}
cout<<endl;
int index;
cin>>index;
for(int i=0;i<index;i++){
skac.pop();
}
cout<<skac.top();
}
if(shuju=='D'){
int len;
cin>>len;
stack<double> skac;
for(int i=0;i<len;i++){
double val;
cin>>val;
skac.push(val);
}
stack<double >tem=skac;
for(int i=0;i<len;i++){
cout<<tem.top()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
double val;
cin>>val;
skac.push(val);
len++;
}else if(rule=='R'){
skac.pop();
len--;
}
stack<double >tem1=skac;
for(int i=0;i<len;i++){
cout<<tem1.top()<<' ';
tem1.pop();
}
cout<<endl;
int index;
cin>>index;
for(int i=0;i<index;i++){
skac.pop();
}
cout<<skac.top();
}
if(shuju=='C'){
int len;
cin>>len;
stack<char> skac;
for(int i=0;i<len;i++){
char val;
cin>>val;
skac.push(val);
}
stack<char>tem=skac;
for(int i=0;i<len;i++){
cout<<tem.top()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
char val;
cin>>val;
skac.push(val);
len++;
}else if(rule=='R'){
skac.pop();
len--;
}
stack<char>tem1=skac;
for(int i=0;i<len;i++){
cout<<tem1.top()<<' ';
tem1.pop();
}
cout<<endl;
int index;
cin>>index;
for(int i=0;i<index;i++){
skac.pop();
}
cout<<skac.top();
}
}
if(jiegou=='Q'){
if(shuju=='I'){
int len;
cin>>len;
queue<int>que;
for(int i=0;i<len;i++){
int val;
cin>>val;
que.push(val);
}
queue<int>tem=que;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
int val;
cin>>val;
que.push(val);
len++;
queue<int>tem1=que;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop();
}
cout<<endl;
}else if(rule=='R'){
que.pop();
len--;
queue<int>tem2=que;
for(int i=0;i<len;i++){
cout<<tem2.front()<<' ';
tem2.pop();
}
cout<<endl;
}
int index;
cin>>index;
for(int i=0;i<index;i++){
que.pop();
}
cout<<que.front();
}
if(shuju=='D'){
int len;
cin>>len;
queue<double>que;
for(int i=0;i<len;i++){
double val;
cin>>val;
que.push(val);
}
queue<double>tem=que;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
double val;
cin>>val;
que.push(val);
len++;
queue<double>tem1=que;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop();
}
cout<<endl;
}else if(rule=='R'){
que.pop();
len--;
queue<double>tem2=que;
for(int i=0;i<len;i++){
cout<<tem2.front()<<' ';
tem2.pop();
}
cout<<endl;
}
int index;
cin>>index;
for(int i=0;i<index;i++){
que.pop();
}
cout<<que.front();
}
if(shuju=='C'){
int len;
cin>>len;
queue<char>que;
for(int i=0;i<len;i++){
char val;
cin>>val;
que.push(val);
}
queue<char>tem=que;
for(int i=0;i<len;i++){
cout<<tem.front()<<' ';
tem.pop();
}
cout<<endl;
char rule;
cin>>rule;
if(rule=='A'){
char val;
cin>>val;
que.push(val);
len++;
queue<char>tem1=que;
for(int i=0;i<len;i++){
cout<<tem1.front()<<' ';
tem1.pop();
}
cout<<endl;
}else if(rule=='R'){
que.pop();
len--;
queue<char>tem2=que;
for(int i=0;i<len;i++){
cout<<tem2.front()<<' ';
tem2.pop();
}
cout<<endl;
}
int index;
cin>>index;
for(int i=0;i<index;i++){
que.pop();
}
cout<<que.front();
}
}
return 0;
}
#include <bits/stdc++.h>
using namespace std;
template <class T>
struct Node {
T data;
Node<T>* next;
Node(const T& d = T(), Node<T>* n = nullptr) : data(d), next(n) {}
};
template <class T>
class List {
protected:
Node<T>* head;
int len;
public:
List() : head(nullptr), len(0) {}
virtual ~List() {
clear();
}
void clear() {
while (head) {
Node<T>* p = head;
head = head->next;
delete p;
}
len = 0;
}
virtual void Insert(const T& x) {
Node<T>* node = new Node<T>(x);
if (!head || x < head->data) {
node->next = head;
head = node;
} else {
Node<T>* p = head;
while (p->next && p->next->data <= x) {
p = p->next;
}
node->next = p->next;
p->next = node;
}
len++;
}
virtual void Remove(const T& x) {
while (head && head->data == x) {
Node<T>* p = head;
head = head->next;
delete p;
len--;
}
Node<T>* cur = head;
while (cur && cur->next) {
if (cur->next->data == x) {
Node<T>* p = cur->next;
cur->next = p->next;
delete p;
len--;
} else {
cur = cur->next;
}
}
}
T& operator[](int index) {
Node<T>* p = head;
for (int i = 0; i < index; i++) {
p = p->next;
}
return p->data;
}
friend ostream& operator<<(ostream& os, const List<T>& list) {
Node<T>* p = list.head;
while (p) {
os << p->data;
if (p->next) os << ' ';
p = p->next;
}
return os;
}
};
template <class T>
class Stack : public List<T> {
public:
void Insert(const T& x) override {
Node<T>* node = new Node<T>(x, this->head);
this->head = node;
this->len++;
}
void Remove(const T& x) override {
(void)x;
if (!this->head) return;
Node<T>* p = this->head;
this->head = this->head->next;
delete p;
this->len--;
}
};
template <class T>
class Queue : public List<T> {
public:
void Insert(const T& x) override {
Node<T>* node = new Node<T>(x);
if (!this->head) {
this->head = node;
} else {
Node<T>* p = this->head;
while (p->next) p = p->next;
p->next = node;
}
this->len++;
}
void Remove(const T& x) override {
(void)x;
if (!this->head) return;
Node<T>* p = this->head;
this->head = this->head->next;
delete p;
this->len--;
}
};
template <class T>
void solve(char kind) {
int n;
cin >> n;
List<T>* ds;
if (kind == 'L') ds = new List<T>();
else if (kind == 'S') ds = new Stack<T>();
else ds = new Queue<T>();
for (int i = 0; i < n; i++) {
T x;
cin >> x;
ds->Insert(x);
}
cout << *ds << endl;
char op;
cin >> op;
T a{};
if (op == 'A') {
cin >> a;
ds->Insert(a);
} else {
if (kind == 'L') {
cin >> a;
ds->Remove(a);
} else {
ds->Remove(a);
}
}
cout << *ds << endl;
int index;
cin >> index;
cout << (*ds)[index] << endl;
delete ds;
}
int main() {
char kind, type;
cin >> kind;
cin >> type;
if (type == 'I') solve<int>(kind);
else if (type == 'D') solve<double>(kind);
else solve<char>(kind);
return 0;
}
25.附加题八云蓝的结界维护工作
输入:
2
4
FOR i : 1 -> 10 i += 1 :
FOR j : 1 -> 15 j += 1 :
FOR k : 1 -> 20 k += 1 :
FOR p : 1 -> 25 p += 1 :
sum+=2i+j3+151+2p0+4k+5p;
2
FOR _ii_1 : 1 -> 20510+020000 _ii_1 += 21 :
FOR jjjj___asdasd : 11 -> 377 jjjj___asdasd += 712 :
sum+=11*_ii_1+111*_ii_1+222*_ii_1+123*_ii_1+312*_ii_1+666+451*_ii_1+162*_ii_1+3jjjj___asdasd2+100*_ii_1+100*_ii_1+2jjjj___asdasd+205jjjj___asdasd+111*jjjj___asdasd+159;
for(int _ii_1 = 1; _ii_1 <= 20510; _ii_1 += 2){
for(int jjjj___asdasd = 1; jjjj___asdasd <= 377; jjjj___asdasd += 14){
sum+=11*_ii_1+111*_ii_1+222*_ii_1+123*_ii_1+312*_ii_1+666+451*_ii_1+162*_ii_1+3jjjj___asdasd2+100*_ii_1+100*_ii_1+2jjjj___asdasd+205jjjj___asdasd+111*jjjj___asdasd+159;
24.1链表合并
#include<iostream>
using namespace std;
struct node {
int val;
node* next;
node(int a) :val(a), next(NULL) {}
};
class list {
public:
node* head;
node* tail;
int count;
list() :head(NULL), tail(NULL), count(0) {}
friend ostream& operator<<(ostream& cout, const list& l);
friend istream& operator>>(istream& cin, list& l);
void pushback(int val) {
node* newnode = new node(val);
if (tail == NULL) {
tail = newnode;
head = newnode;
count++;
return;
}
tail->next = newnode;
tail = newnode;
count++;
return;
}
void rearrange() {
list l1;
list l2;
int index = 0;
node* curr = head;
while (curr != NULL) {
index++;
if (index % 2 == 1 && curr->val % 2 == 1) {
l1.pushback(curr->val);
}
else if (index % 2 == 0 && curr->val % 2 == 0) {
l2.pushback(curr->val);
}
curr = curr->next;
}
if (l1.head == NULL) {
cout << l2;
return;
}
if (l2.head != NULL) {
l1.tail->next = l2.head;
}
cout << l1;
return;
}
};
ostream& operator<<(ostream& cout, const list& l) {
node* curr = l.head;
if (curr == NULL) {
cout << "NULL";
}
while (curr != NULL) {
cout << curr->val << ' ';
curr = curr->next;
}
return cout;
}
istream& operator>>(istream& cin, list& l) {
int val;
cin >> val;
node* newnode = new node(val);
l.count++;
if (l.tail == NULL) {
l.head = newnode;
l.tail = newnode;
return cin;
}
l.tail->next = newnode;
l.tail = newnode;
return cin;
}
int main() {
int n;
cin >> n;
list test;
for (int i = 0; i < n; i++) {
cin >> test;
}
test.rearrange();
return 0;
}
24.2交通工具租贸
3
C byd qin 5 2
M haojue AFR125X 150 1
B Gaint Quck-E 0 3
#include<iostream>
#include<string>
using namespace std;
class vehicle {
public:
string brand;
string model;
vehicle(string brand, string model) :brand(brand), model(model) {}
virtual double calculatefree(int day) = 0;
virtual void show() = 0;
virtual ~vehicle() {}
};
class car :public vehicle {
public:
int seat;
car(string brand, string model, int seat) :vehicle(brand, model), seat(seat) {}
double calculatefree(int day) {
return day * (300 + 10 * seat);
}
void show() {
cout << "Car" << ' ' << brand << ' ' << model << ' ';
}
};
class moto :public vehicle {
public:
int cc;
moto(string brand, string model, int cc) :vehicle(brand, model), cc(cc) {}
double calculatefree(int day) {
return day * (cc * 0.5);
}
void show() {
cout << "Motorcycle" << ' ' << brand << ' ' << model << ' ';
}
};
class bicycle :public vehicle {
public:
int ise;
bicycle(string brand, string model, int ise) :vehicle(brand, model), ise(ise) {}
double calculatefree(int day) {
if (ise) {
return 50 * day;
}
else { return 20 * day; }
}
void show() {
cout << "Bicycle" << ' ' << brand << ' ' << model << ' ';
if (ise) { cout << "true"<<' '; }
else { cout << "false"<<' '; }
}
};
int main() {
int n;
cin >> n;
for (int i = 0; i < n; i++) {
char rule;
cin >> rule;
if (rule == 'C') {
int day,seat;
string brand, model;
cin >> brand >> model>>seat>>day;
vehicle* mycar = new car(brand, model, seat);
mycar->show(); cout << mycar->calculatefree(day);
cout << endl;
}
else if (rule == 'M') {
int day, cc;
string brand, model;
cin >> brand >> model >> cc >> day;
vehicle* mymo = new moto(brand, model, cc);
mymo->show(); cout << mymo->calculatefree(day);
cout << endl;
}
else if (rule == 'B') {
int day, ise;
string brand, model;
cin >> brand >> model >> ise >> day;
vehicle* mybic = new bicycle(brand, model, ise);
mybic->show(); cout << mybic->calculatefree(day);
cout << endl;
}
}
}
24.3容器模板类
这种循环直到输入某一个值停记得在while中cin>>rule;
#include <iostream>
using namespace std;
template<class T>
class MyContainer {
private:
T* data;
int len;
public:
MyContainer(T array[], int n) {
len = n;
data = new T[len];
for (int i = 0; i < len; i++) {
data[i] = array[i];
}
}
~MyContainer() {
delete[] data;
}
void add(const T& value) {
T* newData = new T[len + 1];
for (int i = 0; i < len; i++) {
newData[i] = data[i];
}
newData[len] = value;
delete[] data;
data = newData;
len++;
}
bool remove(int idx) {
if (idx < 0 || idx >= len) {
return false;
}
T* newData = new T[len - 1];
for (int i = 0; i < idx; i++) {
newData[i] = data[i];
}
for (int i = idx + 1; i < len; i++) {
newData[i - 1] = data[i];
}
delete[] data;
data = newData;
len--;
return true;
}
bool empty() {
return len == 0;
}
int size() {
return len;
}
void display() {
if (empty()) {
cout << "None" << endl;
return;
}
cout << "[";
for (int i = 0; i < len; i++) {
cout << data[i];
if (i != len - 1) {
cout << ",";
}
}
cout << "]" << endl;
}
void clear() {
delete[] data;
data = nullptr;
len = 0;
}
};
template<class T>
void solve(MyContainer<T>& container) {
char op;
while (cin >> op) {
if (op == 's') {
break;
} else if (op == 'd') {
container.display();
} else if (op == 'i') {
T x;
cin >> x;
container.add(x);
} else if (op == 'o') {
int idx;
cin >> idx;
if (container.empty()) {
cout << "None" << endl;
} else if (!container.remove(idx)) {
cout << "BoundsLimit" << endl;
}
} else if (op == 'c') {
container.clear();
}
}
}
int main() {
int iarray[] = {0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89};
float farray[] = {0, 0.125, 0.25, 0.375, 0.5, 0.625, 0.75, 0.875, 1.0};
char carray[] = "I_love_Nankai_University";
MyContainer<int> intContainer(iarray, 12);
MyContainer<float> floatContainer(farray, 9);
MyContainer<char> charContainer(carray, 24);
solve(intContainer);
solve(floatContainer);
solve(charContainer);
return 0;
}
#include<iostream>
#include<string>
using namespace std;
template<class T>
class mycontainer{
public:
T* arr;
int len;
mycontainer(T array[],int len):len(len){
arr=new T[len];
for(int i=0;i<len;i++){
arr[i]=array[i];
}
}
void add(const T& value){
T*newdata=new T [len+1];
for(int i=0;i<len;i++){
newdata[i]=arr[i];
}
newdata[len]=value;
delete[] arr;
arr=newdata;
len++;
}
bool remove(int idx){
if(len==0){
cout<<"None"<<endl;
return false;
}
if(idx<0 || idx>len-1){
cout<<"BoundsLimit"<<endl;
return false;
}
T*newdata=new T [len-1];
for(int i=0;i<idx;i++){
newdata[i]=arr[i];
}
for(int i=idx;i<len-1;i++){
newdata[i]=arr[i+1];
}
delete[] arr;
arr=newdata;
len--;
}
bool empty(){
if(count==0){return true;}
return false;
};
int size(){
return count;
};
void display(){
if(len==0){
cout<<"None"<<endl;
return;
}
cout<<'['<<arr[0];
for(int i=1;i<len;i++){
cout<<','<<arr[i];
}
cout<<']'<<endl;
};
void clear(){
delete[] arr;
arr=NULL;
len=0;
}
};
int main(){
int iarray[]={0,1,1,2,3,5,13,21,34,55,89};
float farray[]={0,0.125,0.25,0.375,0.5,0.625,0.75,0.875,1.0};
char carray[]="I_love_Nankai_University";
mycontainer<int> intcon(iarray,11);
mycontainer<float>floatcon(farray,9);
mycontainer<char>charcon(carray,24);
char intrule;
cin>>intrule;
while(intrule!='s'){
if(intrule=='d'){
intcon.display();
}else if(intrule=='i'){
int tem;
cin>>tem;
intcon.add(tem);
}else if(intrule=='o'){
int tem;
cin>>tem;
intcon.remove(tem);
}else if(intrule=='c'){
intcon.clear();
}
cin>>intrule;
}
char floatrule;
cin>>floatrule;
while(floatrule!='s'){
if(floatrule=='d'){
floatcon.display();
}else if(floatrule=='i'){
float tem;
cin>>tem;
floatcon.add(tem);
}else if(floatrule=='o'){
int tem;
cin>>tem;
floatcon.remove(tem);
}else if(floatrule=='c'){
floatcon.clear();
}
cin>>floatrule;
}
char charrule;
cin>>charrule;
while(charrule!='s'){
if(charrule=='d'){
charcon.display();
}else if(charrule=='i'){
char tem;
cin>>tem;
charcon.add(tem);
}else if(charrule=='o'){
int tem;
cin>>tem;
charcon.remove(tem);
}else if(charrule=='c'){
charcon.clear();
}
cin>>charrule;
}
system("pause");
return 0;
}
23.1圆形类
签到题,嘿嘿,代码就不写了
23.2水果类继承多态
#include <iostream>
#include <iomanip>
using namespace std;
class Fruit {
protected:
int Price;
int Weight;
public:
Fruit(int w, int p) {
Weight = w;
Price = p;
}
virtual double SumMoney() = 0;
virtual ~Fruit() {}
};
class Apple : public Fruit {
public:
Apple(int w, int p) : Fruit(w, p) {}
double SumMoney() {
return Price * Weight * 0.8;
}
};
class Banana : public Fruit {
public:
Banana(int w, int p) : Fruit(w, p) {}
double SumMoney() {
return Price * Weight / 2.0;
}
};
class Orange : public Fruit {
public:
Orange(int w, int p) : Fruit(w, p) {}
double SumMoney() {
if (Weight >= 10) {
return Weight * Price / 2.0;
} else if (Weight >= 5) {
return Weight * Price * 0.75;
} else {
return Weight * Price;
}
}
};
int main() {
char c;
int w, p;
double total = 0;
while (cin >> c) {
if (c == 'q') {
break;
}
cin >> w >> p;
Fruit* fruit = nullptr;
if (c == 'a') {
fruit = new Apple(w, p);
} else if (c == 'b') {
fruit = new Banana(w, p);
} else if (c == 'o') {
fruit = new Orange(w, p);
}
if (fruit != nullptr) {
total += fruit->SumMoney();
delete fruit;
}
}
cout << fixed << setprecision(2) << total << endl;
return 0;
}
23.3单向列表
这个怎么实现,重载运算符只接受两个头指针,那合并的链表我要新建一个链表对象,如果在函数内创建,出函数就销毁了,怎么办
动态对象,建立在堆上
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int v = 0) : val(v), next(nullptr) {}
};
class LinkedList {
private:
ListNode* head;
public:
LinkedList() : head(nullptr) {}
ListNode* getHead() const {
return head;
}
void pushBack(int val) {
ListNode* node = new ListNode(val);
if (head == nullptr) {
head = node;
return;
}
ListNode* cur = head;
while (cur->next != nullptr) {
cur = cur->next;
}
cur->next = node;
}
static ListNode* reverse(ListNode* head) {
ListNode* prev = nullptr;
ListNode* cur = head;
while (cur != nullptr) {
ListNode* nextNode = cur->next;
cur->next = prev;
prev = cur;
cur = nextNode;
}
return prev;
}
static void print(ListNode* head) {
ListNode* cur = head;
while (cur != nullptr) {
cout << cur->val;
if (cur->next != nullptr) cout << " ";
cur = cur->next;
}
cout << endl;
}
ListNode* operator+(LinkedList& other) {
ListNode* p = reverse(this->head);
ListNode* q = reverse(other.head);
ListNode dummy;
ListNode* tail = &dummy;
int carry = 0;//进位
while (p != nullptr || q != nullptr || carry != 0) {
int sum = carry;
if (p != nullptr) {
sum += p->val;
p = p->next;
}
if (q != nullptr) {
sum += q->val;
q = q->next;
}
carry = sum / 10;
tail->next = new ListNode(sum % 10);
tail = tail->next;
}
return dummy.next;
}
};
int main() {
int a, b;
cin >> a >> b;
LinkedList A, B;
for (int i = 0; i < a; i++) {
int x;
cin >> x;
A.pushBack(x);
}
for (int i = 0; i < b; i++) {
int x;
cin >> x;
B.pushBack(x);
}
ListNode* result = A + B;
LinkedList::print(result);
return 0;
}
23.4栈模板类
#include <iostream>
using namespace std;
const int MAXLEN = 20;
template<class T>
class MyStack {
private:
T data[MAXLEN];
int topIndex;
public:
MyStack(T array[], int len) {
topIndex = -1;
for (int i = 0; i < len && i < MAXLEN; i++) {
data[++topIndex] = array[i];
}
}
void push(const T& value) {
if (topIndex == MAXLEN - 1) {
cout << "FULL" << endl;
return;
}
data[++topIndex] = value;
}
T pop() {
if (empty()) {
cout << "None" << endl;
return T();
}
return data[topIndex--];
}
bool empty() {
return topIndex == -1;
}
int count() {
return topIndex + 1;
}
void show() {
if (empty()) {
cout << "None" << endl;
return;
}
for (int i = 0; i <= topIndex; i++) {
cout << data[i] << " ";
}
cout << count() << endl;
}
void clear() {
topIndex = -1;
}
};
template<class T>
void solve(MyStack<T>& stack) {
char op;
while (cin >> op) {
if (op == 's') {
break;
} else if (op == 'd') {
stack.show();
} else if (op == 'i') {
T x;
cin >> x;
stack.push(x);
} else if (op == 'o') {
int x;
cin >> x;
for (int i = 0; i < x; i++) {
if (stack.empty()) {
cout << "None" << endl;
break;
}
stack.pop();
}
} else if (op == 'c') {
stack.clear();
}
}
}
int main() {
int iarray[] = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37};
char carray[] = "this_is_a_teststring";
MyStack<int> intStack(iarray, 12);
MyStack<char> charStack(carray, 20);
solve(intStack);
solve(charStack);
return 0;
}
22.3链表类模板
#include <iostream>
using namespace std;
template<class T>
class list {
private:
struct node {
T data;
node* next;
};
node* head;
node* tail;
public:
list() {
head = nullptr;
tail = nullptr;
}
void Insert(T item) {
node* p = new node;
p->data = item;
p->next = head;
head = p;
if (tail == nullptr) {
tail = p;
}
}
void Append(T item) {
node* p = new node;
p->data = item;
p->next = nullptr;
if (head == nullptr) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
int count() {
int cnt = 0;
node* p = head;
while (p != nullptr) {
cnt++;
p = p->next;
}
return cnt;
}
void htot() {
if (head == nullptr || head == tail) {
return;
}
node* oldHead = head;
head = head->next;
oldHead->next = nullptr;
tail->next = oldHead;
tail = oldHead;
}
void ttoh() {
if (head == nullptr || head == tail) {
return;
}
node* prev = nullptr;
node* cur = head;
while (cur->next != nullptr) {
prev = cur;
cur = cur->next;
}
prev->next = nullptr;
tail = prev;
cur->next = head;
head = cur;
}
void display() {
if (head == nullptr) {
cout << "emptylist" << endl;
return;
}
node* p = head;
while (p != nullptr) {
cout << p->data;
if (p->next != nullptr) {
cout << " ";
}
p = p->next;
}
cout << endl;
}
void SortList() {
int n = count();
if (n == 0) {
cout << "emptylist" << endl;
return;
}
T* arr = new T[n];
node* p = head;
for (int i = 0; i < n; i++) {
arr[i] = p->data;
p = p->next;
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cout << arr[i];
if (i != n - 1) {
cout << " ";
}
}
cout << endl;
delete[] arr;
}
};
int main() {
string type;
int n;
cin >> type;
cin >> n;
if (type == "int") {
list<int> link1;
list<int> link2;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
link1.Append(x);
link2.Insert(x);
}
cout << link1.count() << endl;
link1.display();
link1.ttoh();
link1.display();
cout << link2.count() << endl;
link2.display();
link2.htot();
link2.display();
link1.SortList();
} else if (type == "char") {
list<char> link1;
list<char> link2;
for (int i = 0; i < n; i++) {
char x;
cin >> x;
link1.Append(x);
link2.Insert(x);
}
cout << link1.count() << endl;
link1.display();
link1.ttoh();
link1.display();
cout << link2.count() << endl;
link2.display();
link2.htot();
link2.display();
link1.SortList();
}
return 0;
}
22.2抽象基类file类
#include <iostream>
#include <string>
using namespace std;
class File {
protected:
string filename;
int filesize;
public:
File(string name, int size) {
filename = name;
filesize = size;
}
virtual void UpdateFile() = 0;
virtual void show() = 0;
virtual ~File() {}
};
string getEncodeName(int code) {
if (code == 0) return "ASCII";
if (code == 1) return "UNICODE";
if (code == 2) return "UTF8";
if (code == 3) return "ANSI";
return "";
}
class ChangeEncode_name : public File {
private:
int fileEncode;
public:
ChangeEncode_name(string name, int size, int encode)
: File(name, size) {
fileEncode = encode;
}
void UpdateFile() {
cin >> filename >> fileEncode;
}
void show() {
cout << "change_encodeAndname:"
<< filename << " "
<< filesize << " "
<< getEncodeName(fileEncode) << endl;
}
};
class ChangeEncode_size : public File {
private:
int fileEncode;
public:
ChangeEncode_size(string name, int size, int encode)
: File(name, size) {
fileEncode = encode;
}
void UpdateFile() {
cin >> filesize >> fileEncode;
}
void show() {
cout << "change_encodeAndsize:"
<< filename << " "
<< filesize << " "
<< getEncodeName(fileEncode) << endl;
}
};
int main() {
string name;
int size;
int encode;
cin >> name >> size >> encode;
char op;
cin >> op;
File* file = nullptr;
if (op == 'N') {
file = new ChangeEncode_name(name, size, encode);
} else if (op == 'S') {
file = new ChangeEncode_size(name, size, encode);
} else {
cout << "No such operation!" << endl;
return 0;
}
file->UpdateFile();
file->show();
delete file;
return 0;
}
#include <iostream>
using namespace std;
template<class T>
class list {
private:
struct node {
T data;
node* next;
};
node* head;
node* tail;
public:
list() {
head = nullptr;
tail = nullptr;
}
void Insert(T item) {
node* p = new node;
p->data = item;
p->next = head;
head = p;
if (tail == nullptr) {
tail = p;
}
}
void Append(T item) {
node* p = new node;
p->data = item;
p->next = nullptr;
if (head == nullptr) {
head = tail = p;
} else {
tail->next = p;
tail = p;
}
}
int count() {
int cnt = 0;
node* p = head;
while (p != nullptr) {
cnt++;
p = p->next;
}
return cnt;
}
void htot() {
if (head == nullptr || head == tail) {
return;
}
node* oldHead = head;
head = head->next;
oldHead->next = nullptr;
tail->next = oldHead;
tail = oldHead;
}
void ttoh() {
if (head == nullptr || head == tail) {
return;
}
node* prev = nullptr;
node* cur = head;
while (cur->next != nullptr) {
prev = cur;
cur = cur->next;
}
prev->next = nullptr;
tail = prev;
cur->next = head;
head = cur;
}
void display() {
if (head == nullptr) {
cout << "emptylist" << endl;
return;
}
node* p = head;
while (p != nullptr) {
cout << p->data;
if (p->next != nullptr) {
cout << " ";
}
p = p->next;
}
cout << endl;
}
void SortList() {
int n = count();
if (n == 0) {
cout << "emptylist" << endl;
return;
}
T* arr = new T[n];
node* p = head;
for (int i = 0; i < n; i++) {
arr[i] = p->data;
p = p->next;
}
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
T temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
for (int i = 0; i < n; i++) {
cout << arr[i];
if (i != n - 1) {
cout << " ";
}
}
cout << endl;
delete[] arr;
}
};
int main() {
string type;
int n;
cin >> type;
cin >> n;
if (type == "int") {
list<int> link1;
list<int> link2;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
link1.Append(x);
link2.Insert(x);
}
cout << link1.count() << endl;
link1.display();
link1.ttoh();
link1.display();
cout << link2.count() << endl;
link2.display();
link2.htot();
link2.display();
link1.SortList();
} else if (type == "char") {
list<char> link1;
list<char> link2;
for (int i = 0; i < n; i++) {
char x;
cin >> x;
link1.Append(x);
link2.Insert(x);
}
cout << link1.count() << endl;
link1.display();
link1.ttoh();
link1.display();
cout << link2.count() << endl;
link2.display();
link2.htot();
link2.display();
link1.SortList();
}
return 0;
}
22.1复数类
#include <iostream>
using namespace std;
class Complex {
private:
int real;
int imag;
public:
Complex(int r = 0, int i = 0) {
real = r;
imag = i;
}
Complex operator-(const Complex& other) {
return Complex(real - other.real, imag - other.imag);
}
Complex operator+(const Complex& other) {
return Complex(real + other.real, imag + other.imag);
}
Complex operator*(const Complex& other) {
int r = real * other.real - imag * other.imag;
int i = real * other.imag + imag * other.real;
return Complex(r, i);
}
void print() {
if (real == 0 && imag == 0) {
cout << 0 << endl;
} else if (imag == 0) {
cout << real << endl;
} else if (real == 0) {
if (imag == 1) {
cout << "i" << endl;
} else if (imag == -1) {
cout << "-i" << endl;
} else {
cout << imag << "i" << endl;
}
} else {
cout << real;
if (imag > 0) {
cout << "+";
}
if (imag == 1) {
cout << "i";
} else if (imag == -1) {
cout << "-i";
} else {
cout << imag << "i";
}
cout << endl;
}
}
};
int main() {
int a, b, c, d;
cin >> a >> b >> c >> d;
Complex x(a, b);
Complex y(c, d);
(x - y).print();
(x + y).print();
(x * y).print();
return 0;
}
for循环中的细节
注:int声明,例如 : for(int i=0;i<n;i++){........;}
情况1(有int声明):
main函数作用域: i(未初始化,垃圾值)
↓
for循环作用域: i=2 → i=3 → i=4 ... 循环结束,这个i被销毁
↑
b[i-2]='\0' ← 这里用的是main函数的垃圾值i
情况2(无int声明):
main函数作用域: i=2 → i=3 → i=4 ... → i=n(循环结束时的值)
↓ ↓ ↓
for循环内 for循环内 b[i-2]='\0' ← 这里i=n,正确!
#include<iostream>
using namespace std;
int main()
{
char a[20],b[20];
int n,i;
cin>>a;
n=strlen(a);
for(i=2;i<n;i++)
{
b[i-2]=a[i];
}
b[i-2]='\0';
cout<<b<<endl;
cout<<i;//无int声明才有意义
}
#include <iostream>
#include <string>
#include<vector>
#include <algorithm>
using namespace std;
bool isPalindrome(const string& s) {
int n = s.length();
for (int i = 0; i < n / 2; i++) {
if (s[i] != s[n - 1 - i])
return false;
}
return true;
}
int main() {
int n;
vector <string> judge;
cin >> n;
while (n--) {
string s;
cin >> s;
int len = s.length();
if (len < 4) {
cout << "No" << endl;
continue;
}
bool found = false;
for (int i = 2; i <= len - 2; i++) {
string left = s.substr(0, i);
string right = s.substr(i);
if (isPalindrome(left) && isPalindrome(right)) {
found = true;
break;
}
}
if(found)
{
judge.push_back("Yes");
}
else{
judge.push_back("No");
}
}
for(int i=0;i<judge.size();i++)
{
cout<<judge[i]<<endl;
}
return 0;
}
Box类
设计一个立方体类Box,它能计算并输出立方体的体积和表面积。要求:
(1)包含成员变量m_a(立方体边长)。
(2)包含函数SetA(double a)(设置立方体边长)、GetVolume()(计算体积)、GetArea()(计算表面积)。
(3) 输出结果的Display函数:格式化显示边长、体积、表面积
(4)设计测试用主函数main(),用来测试Box类。
#include<iostream>
using namespace std;
class Box {
private:
double m_a;//立方体边长
public:
Box():m_a(0.0){}
Box& SetA(double a);//设置立方体的边长
double GetVolume();//计算体积
double GetArea();//计算表面积
void Display();//输出计算结果
};
Box& Box::SetA(double a) {
m_a = a;
return *this;
}
double Box::GetVolume() {
return m_a * m_a * m_a;
}
double Box::GetArea() {
return 6 * m_a * m_a;
}
void Box::Display() {
cout << "=======================" << endl;
cout << "立方体的边长为:" << m_a << endl;
cout << "立方体的表面积为:" << GetArea() << endl;
cout << "立方体的体积为:" << GetVolume() << endl;
cout << "=======================" << endl;
}
int main() {
Box a, b;
a.SetA(2);
a.Display();
b.Display();
return 0;
}
Rectangle类
设计一个Rectangle类。要求:
(1)包含两个成员变量m_length和m_width,其默认值为1。
(2)包含成员函数Perimeter()计算长方形的周长,Area()计算长方形面积。
(3)包含成员函数SetWidth()和GetWidth()用来设置和得到m_width的值,SetLength()和GetLength()用来设置和得到m_length的值。Set…()函数应验证m_length和m_width均为0.0到20.0之间的浮点数。
(4)编写主函数,测试Rectangle类
#include<iostream>
#include<iomanip>
using namespace std;
class Rectangle {
private:
double m_length;
double m_width;
public:
Rectangle() :m_length(1.0), m_width(1.0) {}
Rectangle& SetWidth(const double w);
double GetWidth();
Rectangle& Setlength(const double l);
double Getlength();
double Perimeter();//计算长方形周长
double Area();//计算长方形面积
};
Rectangle& Rectangle::SetWidth(const double w) {
m_width = w;
return *this;
}
double Rectangle::GetWidth() {
return m_width;
}
Rectangle& Rectangle::Setlength(const double l) {
m_length = l;
return *this;
}
double Rectangle::Getlength() {
return m_length;
}
double Rectangle::Perimeter() {
return 2 * (m_length + m_width);
}
double Rectangle::Area() {
return m_length * m_width;
}
int main() {
Rectangle a, b;
a.Setlength(6).SetWidth(4);
b.Setlength(4.0).SetWidth(2.2);
cout << "a的面积:" << a.Area() << endl << "a的周长" << a.Perimeter() << endl;
cout << left << setfill('-') << setw(20) << "b的宽度:" << setw(20) << b.GetWidth() << endl;
;
cout << left << setfill('-') << setw(20) << "b的长度:" << setw(20) << b.Getlength();
return 0;
}
User类
编写一个程序,在已设置好若干个用户名/口令后,通过输入用户名,查找对应的口令,连续执行这一过程直到用户输入结束标记“end”为止。要求:
(1)设计一个User类,成员变量包含用户名和口令;另有一个无参构造函数和SetName()、SetPass()、GetName()、GetPass()四个成员函数,用于设置和获取用户名和口令,并根据需要编写析构函数。
(2)在主函数中设计一个对象数组,当用户输入一个用户名后,在对象数组中查找,找到后输出对应的口令,找不到时输出相应的提示信息。
#include<iostream>
#include<string>
using namespace std;
class User {
private:
string m_name;
string m_pass;
public:
User():m_name("no meaning"),m_pass("no meaning") {}
User& SetName(const string&);
User& SetPass(const string&);
string GetName()const;
string GetPass()const;
~User() {}
};
User& User::SetName(const string&str) {
m_name = str;
return this;
}
User& User::SetPass(const string&str){
m_pass = str;
return this;
}
string User::GetName()const{
return m_name;
}
string User::GetPass()const {
return m_pass;
}
int main() {
User users[3];
users[0].SetName("zhangsan");
users[0].SetPass("123456");
// 设置第二个用户
users[1].SetName("lisi");
users[1].SetPass("654321");
// 设置第三个用户
users[2].SetName("wangwu");
users[2].SetPass("888888");
string input=" ";
while (input != "end") {
bool isfind = false;//循环内的bool类型用来标记寻找结果
cin >> input;
if (input == "end") {
break;
}
for (int i = 0; i < 3; i++) {
if (users[i].GetName() == input) {
cout << "口令是:" << users[i].GetPass() << endl;
isfind = true;
break;
}
}
if (isfind == false) {
cout << "没有找到" << endl;
}
}
return 0;
}
Person类
编写一个Person类,包括:
1、普通数据成员:姓名,性别,年龄。
2、三个构造函数:无参数构造函数,有参数构造函数(参数:姓名的指针,年龄,性别),拷贝构造函数。
3、析构函数,输出人员信息函数print()。
编写main()函数,分别调用三种构造函数,创建三个对象P1、P2、P3,其中P3的创建是用P2通过深拷贝复制得到的。
#include<iostream>
#include<string>
using namespace std;
enum sex { male, female };
class Person {
private:
string m_name;
sex m_sex;
int m_age;
public:
Person();
Person(string, int, sex);
Person(const Person&);
~Person();
void print();
};
Person::Person() :m_name(nullptr), m_sex(male), m_age(0) {};
Person::Person(string* p, int age, sex m_sex) : m_age(age) {
this->m_sex = m_sex;
if (p != nullptr) {
m_name = new string(p);
}
else {
m_name = nullptr;
}
}
Person::Person(const Person& P) {
if (P.m_name != nullptr) {
m_name = new string((P.m_name));
}
else { m_name = nullptr; }
m_sex = P.m_sex;
m_age = P.m_age;
}
Person::~Person() {
if (m_name != nullptr) {
delete m_name;
m_name = nullptr;
}
}
void Person::print() {
// 1. 姓名输出:处理空指针,避免崩溃
cout << "姓名:";
if (m_name != nullptr) {
cout << *m_name; // 解引用获取姓名内容
}
else {
cout << "空"; // 无姓名时输出「空」
}
// 2. 性别输出:转换枚举值为「男/女」
cout << " 性别:";
if (m_sex == male) {
cout << "男";
}
else if (m_sex == female) {
cout << "女";
}
else {
cout << "未知"; // 兼容异常情况
}
// 3. 补充年龄输出(之前缺失的部分)
cout << " 年龄:" << m_age << endl;
}
Stud类
编写一个程序,输入N个学生数据,包括学号、姓名、成绩,输出这些学生数据并计算平均分。要求:
(1)设计一个学生类Stud,除了包括学号、姓名和成绩数据成员外,有两个静态变量分别存放总分和人数。
(2)有普通成员函数SetData()和Disp(),分别用于给数据成员赋值和输出数据成员的值。友元函数Com()用来比较两个学生的成绩大小,另有一个静态成员函数Avg(),它用于计算平均分。
(3)在main()函数中定义一个对象数组用于存储输入的学生数据。
#include<iostream>
#include<string>
using namespace std;
class Stud {
private:
int m_idex;
string m_name;
float m_score;
static float totalm;
static float totals;
public:
Stud() {};
Stud& SetData(int ,string,float);
void Disp()const;
static float Avg();
friend void Com(const Stud& a, const Stud& b);
};
float Stud::totalm = 0;
float Stud::totals = 0;
Stud& Stud::SetData(int idex, string name, float score){
m_idex = idex;
m_name = name;
m_score = score;
totalm++;
totals += score;
return *this;
}
void Stud::Disp()const {
cout << "学号:" << m_idex << " " << "姓名:" << m_name << " " << "成绩:" << m_score << endl;
return;
}
float Stud::Avg() {
return totals / totalm;
}
void Com(const Stud& a, const Stud& b) {
Stud tem = a.m_score > b.m_score ? a : b;
cout << "成绩好的学生为" << tem.m_name;
}
int main() {
int N;
cin >> N;
if (N <= 0) {
cout << "人数输入不正确" << endl;
return 0;
}
Stud* test = new Stud[N];
for (int i = 0; i < N; i++) {
int idex;
string name;
float score;
cout << "请输入第" << i+1 << "个学生的信息" << endl;
cin >> idex >> name >> score;
test[i].SetData(idex,name,score);
}
cout << "======" << "统计结果" << "======" << endl;
cout << "平均成绩:" << Stud::Avg() << endl;
Com(test[0], test[1]);
delete []test;
return 0;
}
日期类
include<iostream>
using namespace std;
class Date {
private:
int year;
int month;
int day;
// 判断是否为闰年
bool isLeapYear(int y) {
return (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0);
}
// 获取指定月份的天数
int getDaysInMonth(int y, int m) {
int days[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
// 闰年2月29天
if (m == 2 && isLeapYear(y)) return 29;
return days[m];
}
public:
// 初始化日期
Date(int y, int m, int d) : year(y), month(m), day(d) {}
// 显示日期函数
void display() {
cout << year << "-" << month << "-" << day << endl;
}
// 加天数函数
Date addDays(int days) {
Date res = *this;
res.day += days;
while (res.day > getDaysInMonth(res.year, res.month)) {
res.day -= getDaysInMonth(res.year, res.month);
res.month++;
if (res.month > 12) {
res.month = 1;
res.year++;
}
}
return res;
}
// 减天数函数
Date subDays(int days) {
Date res = *this;
res.day -= days;
while (res.day <= 0) {
res.month--;
if (res.month < 1) {
res.month = 12;
res.year--;
}
res.day += getDaysInMonth(res.year, res.month);
}
return res;
}
};
int main() {
int y, m, d;
int sub_val, add_val;
// 输入:年 月 日 减少天数 增加天数
cin >> y >> m >> d >> sub_val >> add_val;
// 创建日期对象
Date dt(y, m, d);
// 输出当前日期
dt.display();
// 输出减少天数后的日期
Date dtSub = dt.subDays(sub_val);
dtSub.display();
// 输出增加天数后的日期
Date dtAdd = dt.addDays(add_val);
dtAdd.display();
return 0;
}
学生类
stu1 100001 80 67
stu2 100002 93 77
stu3 100003 65 64
stu4 100004 99 78
stu5 100005 84 92
stu6 100006 55 76
stu7 100007 75 82
stu8 100008 89 87
stu9 100009 93 81
stu10 100010 91 72
82.4
77.6
stu4 100004 99 78 177
stu5 100005 84 92 176
stu8 100008 89 87 176
必须有拷贝构造函数,因为默认的无对静态变量的处理,而创建临时变量的时候又会调用拷贝构造函数
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <iomanip>
using namespace std;
class CStudent {
private:
string name;
string id;
int math;
int english;
// 静态数据成员
static int count; // 学生总人数
static int mathTotal; // 数学总成绩
static int englishTotal; // 英语总成绩
public:
// 构造函数
CStudent(string n, string i, int m, int e) : name(n), id(i), math(m), english(e) {
count++;
mathTotal += m;
englishTotal += e;
}
// 拷贝构造函数
CStudent(const CStudent& other) : name(other.name), id(other.id),
math(other.math), english(other.english) {
count++;
mathTotal += math;
englishTotal += english;
// cout << "拷贝构造函数被调用" << endl;
}
// 赋值运算符
CStudent& operator=(const CStudent& other) {
if (this != &other) {
// 先减去当前对象的数据
count--;
mathTotal -= math;
englishTotal -= english;
// 拷贝数据
name = other.name;
id = other.id;
math = other.math;
english = other.english;
// 加上新对象的数据
count++;
mathTotal += math;
englishTotal += english;
}
return *this;
}
// 析构函数
~CStudent() {
count--;
mathTotal -= math;
englishTotal -= english;
}
// 设置数学成绩
void setMath(int m) {
mathTotal -= math; // 减去旧成绩
math = m;
mathTotal += math; // 加上新成绩
}
// 设置英语成绩
void setEnglish(int e) {
englishTotal -= english; // 减去旧成绩
english = e;
englishTotal += english; // 加上新成绩
}
// 求本人总成绩
int getTotalScore() const {
return math + english;
}
// 获取姓名
string getName() const {
return name;
}
// 获取学号
string getId() const {
return id;
}
// 获取数学成绩
int getMath() const {
return math;
}
// 获取英语成绩
int getEnglish() const {
return english;
}
// 输出数据
void display() const {
cout << name << " " << id << " " << math << " " << english << " " << getTotalScore() << endl;
}
// 输出数学平均分
static void outputMathAverage() {
if (count == 0) {
cout << "0.0" << endl;
return;
}
double avg = (double)(mathTotal) / count;
cout << fixed << setprecision(1) << avg << endl;
}
// 输出英语平均分
static void outputEnglishAverage() {
if (count == 0) {
cout << "0.0" << endl;
return;
}
double avg = static_cast<double>(englishTotal) / count;
cout << fixed << setprecision(1) << avg << endl;
}
};
// 冒泡排序
void bubbleSort(vector<CStudent>& students) {
int n = students.size();
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n - 1 - i; j++) {
if (students[j].getTotalScore() < students[j + 1].getTotalScore()) {
swap(students[j], students[j + 1]);
}
}
}
}
// 初始化静态数据成员
int CStudent::count = 0;
int CStudent::mathTotal = 0;
int CStudent::englishTotal = 0;
// 比较函数
bool compareStudents(const CStudent& a, const CStudent& b) {
return a.getTotalScore() > b.getTotalScore();
}
int main() {
vector<CStudent> students;
string name, id;
int math, english;
// 输入10名学生的数据
for (int i = 0; i < 10; i++) {
cin >> name >> id >> math >> english;
// 创建对象 构造函数更新静态数据
students.emplace_back(name, id, math, english);
}
// 输出数学平均分
CStudent::outputMathAverage();
// 输出英语平均分
CStudent::outputEnglishAverage();
// 直接对对象进行排序
bubbleSort(students);
// 输出前三名学生信息
for (int i = 0; i < 3; i++) {
students[i].display();
}
return 0;
}
#include<iostream>
#include<string>
#include<vector>
#include<iomanip>
using namespace std;
class CStudent {
private:
string name;
string id;
int math;
int english;
static int count;
static int mathc;
static int englishc;
public:
CStudent(const CStudent&a){
name = a.name;
id = a.id;
math = a.math;
english = a.english;
count++;
mathc += math;
englishc += english;
cout << "拷贝构造函数被调用" << endl;
}
CStudent(string name, string id, int math, int english) :name(name), id(id), math(math), english(english) {
count++;
mathc += math;
englishc += english;
}
~CStudent() {
count--;
mathc -= math;
englishc -= english;
}
void setenglish(int english) {
this->english = english;
}
void setmath(int math) {
this->math = math;
}
int gettotal() {
return math + english;
}
static double eaverage() {
return static_cast<double>(englishc) / count;
}
static double maverage() {
return static_cast<double>(mathc) / count;
}
friend ostream& operator<<(ostream& cout, CStudent);
};
//lamda排序 控制符;
ostream& operator<<(ostream& cout,CStudent student) {
cout << student.name << ' ' << student.id << ' ' << student.math << ' ' << student.english << ' ' << student.gettotal() << endl;
return cout;
}
void bubblesort(vector<CStudent>& students) {
int n = students.size();
for (int i = 0; i < n; i++) {
for (int j = n - 1; j > i; j--) {
if (students[j].gettotal() > students[j - 1].gettotal()) {
CStudent tem = students[j];
students[j] = students[j - 1];
students[j - 1] = tem;
}
}
}
}
int CStudent::count=0;
int CStudent::mathc=0;
int CStudent::englishc=0;
int main() {
vector<CStudent> students;
string name;
string id;
int math;
int english;
for (int i = 0; i < 10; i++) {
cin >> name >> id >> math >> english;
students.emplace_back(name, id, math, english);
}
bubblesort(students);
double m = CStudent::maverage();
double e = CStudent::eaverage();
cout << fixed << setprecision(1) << m << endl << e << endl;
for (int i = 0; i < 3; i++) {
cout << students[i];
}
}
计算器类
#include <iostream>
#include <string>
#include <stack>
#include <iomanip>
using namespace std;
class Calculator {
private:
string expression;
stack<double> numStack; // 操作数栈
stack<char> opStack; // 运算符栈
// 判断字符是否为数字
bool isDigit(char c) {
return (c >= '0' && c <= '9');
}
// 判断运算符优先级
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
// 执行运算
double applyOp(double a, double b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
default: return 0;
}
}
// 将字符串转换为数字
double stringToDouble(const string& str) {
double result = 0.0; // 整数部分
double decimal = 0.0; // 小数部分
int decimalCount = 0; // 小数位数
bool isNegative = false; // 是否是负数
bool isDecimal = false; // 是否是小数部分
int start = 0;
// 处理负号
if (str[0] == '-') {
isNegative = true;
start = 1;
}
for (int i = start; i < str.length(); i++) {
char c = str[i];
if (c == '.') {
isDecimal = true;
decimalCount = 0;
continue;
}
int digit = c - '0'; // 字符转数字
if (!isDecimal) { // 整数部分
result = result * 10 + digit;
} else { // 小数部分
decimalCount++;
decimal = decimal * 10 + digit;
}
}
// 处理小数部分
if (decimalCount > 0) {
double decimalDivisor = 1.0;
for (int i = 0; i < decimalCount; i++) {
decimalDivisor *= 10.0;
}
result = result + decimal / decimalDivisor;
}
return isNegative ? -result : result;
}
// 处理运算符
void processOperator(char op) {
while (!opStack.empty() && precedence(opStack.top()) >= precedence(op)) {
char topOp = opStack.top();
opStack.pop();
double b = numStack.top(); numStack.pop();
double a = numStack.top(); numStack.pop();
// 检查除数是否为0
if (topOp == '/' && b == 0) {
throw "WRONG";
}
double result = applyOp(a, b, topOp);
numStack.push(result);
}
opStack.push(op);
}
public:
Calculator() {}
double calculate(const string& expr) {
expression = expr;
// 清除之前的栈
while (!numStack.empty()) numStack.pop();
while (!opStack.empty()) opStack.pop();
size_t i = 0;
while (i < expression.length()) {
char c = expression[i];
// 处理数字
if (isDigit(c) || (c == '-' && (i == 0 || !isDigit(expression[i-1])))) { // 是数字
// 负号
if (c == '-') {
i++;
}
// 解析数字
string numStr;
if (c == '-') {
numStr += '-';
c = expression[i];
}
while (i < expression.length() && (isDigit(expression[i]) || expression[i] == '.')) {
numStr += expression[i];
i++;
}
double num = stringToDouble(numStr);
numStack.push(num);
continue;
}
// 处理运算符
if (c == '+' || c == '-' || c == '*' || c == '/') {
processOperator(c);
i++;
}
else {
i++; // 跳过其他字符
}
}
// 计算剩余符号
while (!opStack.empty()) {
char op = opStack.top();
opStack.pop();
double b = numStack.top(); numStack.pop();
double a = numStack.top(); numStack.pop();
// 检查除数是否为0
if (op == '/' && b == 0) {
throw "WRONG";
}
double result = applyOp(a, b, op);
numStack.push(result);
}
// 返回结果
if (numStack.size() == 1) {
double result = numStack.top();
return result;
}
else {
throw "WRONG";
}
}
};
int main() {
string expression;
cin >> expression;
Calculator calc;
double result = calc.calculate(expression);
cout << setprecision(2) << result;
return 0;
}
栈类
1 2 3 4 5 3 2 1 0
原始栈序列:1 2 3 4 5 3 2 1
翻转后栈序列:1 2 3 5 4 3 2 1
pop两次后栈序列:1 2 3 5 4 3
#include <iostream>
using namespace std;
#define MAX_SIZE 15
class myStack{
double data[MAX_SIZE];
int top;//栈顶下标
public:
myStack(); //构造函数
bool isEmpty(); //栈空判断
bool isFull(); //栈满判断
int length(); //返回栈中数据数量
bool push(double a); //进栈
double pop(); //出栈
void operator ~(); //运算符重载,倒序翻转栈数据
void printData(); //从0到top打印栈序列,空栈打印"Empty stack"
};
// 构造函数:初始化栈,top指向-1表示空栈
myStack::myStack() {
top = -1;
}
// 判断栈是否为空
bool myStack::isEmpty() {
return top == -1;
}
// 判断栈是否已满
bool myStack::isFull() {
return top == MAX_SIZE - 1;
}
// 返回栈中数据数量
int myStack::length() {
return top + 1;
}
// 进栈操作
bool myStack::push(double a) {
if (isFull()) {
return false; // 栈满,进栈失败
}
data[++top] = a;
return true;
}
// 出栈操作
double myStack::pop() {
if (isEmpty()) {
return -1; // 栈空,返回-1
}
return data[top--];
}
// 运算符重载:倒序翻转栈数据
void myStack::operator~() {
if (isEmpty() || length() == 1) {
return; // 空栈或只有一个元素,不需要翻转
}
int left = 0;
int right = top;
while (left < right) {
// 交换左右两端的元素
double temp = data[left];
data[left] = data[right];
data[right] = temp;
left++;
right--;
}
}
// 打印栈数据(从栈底到栈顶)
void myStack::printData() {
if (isEmpty()) {
cout << "Empty stack" << endl;
return;
}
for (int i = 0; i <= top; i++) {
cout << data[i] << " ";
}
cout << endl;
}
int main(){
myStack stack;
double num;
// 读取输入直到遇到0
while (cin >> num && num != 0) {
if (!stack.push(num)) {
cout << "Stack is full!" << endl;
break;
}
}
// 打印原始栈序列
cout << "原始栈序列:";
stack.printData();
// 倒序翻转
~stack;
// 打印翻转后的栈序列
cout << "翻转后栈序列:";
stack.printData();
// 打印pop后到栈序列
stack.pop();
stack.pop();
cout<< "pop两次后栈序列:";
stack.printData();
return 0;
}
#include <iostream>
using namespace std;
class MyStrArr
{
private:
char **strArr; // 字符指针数组
int count; // 字符串个数
public:
// 构造函数
MyStrArr(char *arr, int n)
{
count = n;
strArr = new char[count];
for(int i = 0; i < count; i++)
{
strArr[i] = arr[i];
}
}
// 数据处理函数
void Fun()
{
for(int i = 0; i < count; i++)
{
char temp[105]; // 临时数组存放保留字符
int k = 0;
// 遍历当前字符串
for(int j = 0; strArr[i][j] != '\0'; j++)
{
// 条件:下标为偶数 且 ASCII 为偶数
if(j % 2 == 0 && ((int)strArr[i][j]) % 2 == 0)
{
temp[k++] = strArr[i][j];
}
}
temp[k] = '\0';
// 排序,冒泡排序
for(int m = 0; m < k - 1; m++)
{
for(int n = 0; n < k - 1 - m; n++)
{
if(temp[n] > temp[n+1])
{
char t = temp[n];
temp[n] = temp[n+1];
temp[n+1] = t;
}
}
}
// 复制回原字符串
int idx = 0;
while(temp[idx] != '\0')
{
strArr[i][idx] = temp[idx];
idx++;
}
strArr[i][idx] = '\0';
}
}
// 输出函数
void Output()
{
for(int i = 0; i < count; i++)
{
if(strArr[i][0] == '\0')
cout << 0 << endl;
else
cout << strArr[i] << endl;
}
}
};
int main()
{
int len;
cin >> len;
char **arr = new char*[len];
for(int i = 0; i < len; i++)
{
arr[i] = new char[105];
cin >> arr[i];
}
MyStrArr obj(arr, len);
obj.Fun();
obj.Output();
return 0;
}
mystrcla类
#include <iostream>
using namespace std;
class myStrCla
{
char str[101]; // 存放字符串(假设字符串不超过 100 个字符)
int len; // 当前字符串的具体长度
public:
// 构造函数,由 s 带来字符串 str 的初值
myStrCla(char * s)
{
len = 0;
while(s[len] != '\0') // 手动计算长度并复制
{
str[len] = s[len];
len++;
}
str[len] = '\0';
}
// 输出函数
void strOut()
{
cout << str << endl;
}
// 判断是否回文
bool strIsPal()
{
int left = 0;
int right = len - 1;
while(left < right)
{
if(str[left] != str[right])
return false;
left++;
right--;
}
return true;
}
};
int main()
{
char s[101];
cin >> s;
myStrCla obj(s);
obj.strOut();
if(obj.strIsPal())
cout << "True";
else
cout << "False";
return 0;
}
队列类
(好像有问题)
#include <iostream>
using namespace std;
const int max_size = 10;
class queue
{
private:
float data[max_size];
int front, rear;//头,尾
int num;
public:
// 构造函数
queue(void)
{
front = rear = -1;
num = 0;
}
// 判断是否为空
bool Empty(void)
{
return num == 0;
}
// 判断是否已满
bool Full(void)
{
return num == max_size;
}
// 入队
void Add(float x)
{
if(!Full())
{
rear++;
data[rear] = x;
num++;
}
}
// 出队
float Delete(void)
{
if(!Empty())
{
front++;
num--;
return data[front];
}
return -1; // 感觉Add和Full这两个条件 题目的描述有问题,常规队列满时,需要进行数据的迁移,否则应写成循环队列(取模的形式)或者链表的形式
}
};
int main()
{
int n;
cin >> n;
queue q;
for(int i = 0; i < n; i++)
{
int op;
cin >> op;
if(op == 0) // 入队
{
float x;
cin >> x;
q.Add(x);
}
else if(op == 1) // 出队
{
if(!q.Empty())
cout << q.Delete() << endl;
}
else if(op == 2) // 判断空
{
cout << (q.Empty() ? 1 : 0) << endl;
}
else if(op == 3) // 判断满
{
cout << (q.Full() ? 1 : 0) << endl;
}
}
return 0;
}