
49d08ca34d455eec7b5b.jpeg "#left")
第5-10题

超爱~ 上午好☀️☀️☀️️
本答案参考通义千问
这是一个C++编程实验题目,涉及到排序算法和文本分析两个部分。以下是针对每个问题的详细解答以及解决方案:
解决方案:
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; ++i) {
for (int j = 0; j < n - i - 1; ++j) {
if (arr[j] > arr[j + 1]) {
// 交换元素
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
int main() {
int arr[10];
// 填充数组
for (int i = 0; i < 10; ++i)
cin >> arr[i];
int n = sizeof(arr) / sizeof(arr[0]);
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
return 0;
}
步骤:
bubbleSort,使用两层循环比较并交换相邻元素。main函数中,读取10个整数并调用bubbleSort函数。解决方案:
#include <iostream>
using namespace std;
// 插入函数
int insertSorted(int arr[], int n, int num) {
int i = n - 1;
while (i >= 0 && arr[i] > num) {
arr[i + 1] = arr[i];
i--;
}
arr[i + 1] = num;
return i + 1;
}
int main() {
int arr[10], num;
// 填充数组
for (int i = 0; i < 10; ++i)
cin >> arr[i];
// 输入需要插入的数
cin >> num;
int index = insertSorted(arr, 10, num);
cout << "Element inserted at index: " << index << endl;
// 打印更新后的数组
for (int i = 0; i < 10; ++i)
cout << arr[i] << " ";
return 0;
}
步骤:
insertSorted函数,找到合适的位置插入数。main中读取已排序数组和新数,调用insertSorted函数并打印结果。解决方案:
#include <iostream>
#include <cctype>
using namespace std;
void countCharacters(string str) {
int uppercase = 0, lowercase = 0, digits = 0, spaces = 0, others = 0;
for (char c : str) {
if (isupper(c))
uppercase++;
else if (islower(c))
lowercase++;
else if (isdigit(c))
digits++;
else if (isspace(c))
spaces++;
else
others++;
}
cout << "Uppercase: " << uppercase << "\n";
cout << "Lowercase: " << lowercase << "\n";
cout << "Digits: " << digits << "\n";
cout << "Spaces: " << spaces << "\n";
cout << "Others: " << others << "\n";
}
int main() {
string article;
// 读取文章
getline(cin, article); // 注意,这里是getline而不是cin,因为我们要读取一行
countCharacters(article);
return 0;
}
步骤:
countCharacters函数,遍历字符串并使用isupper、islower、isdigit和isspace函数统计不同类型的字符。main中读取文章并调用countCharacters函数。确保在实验环境中正确设置并运行这些代码,注意输入格式和文件操作(如果需要从文件读取)。