从键盘输入n个学生的学号和成绩,计算他们的平均成绩,并列出成绩最好的前t名学生的学号和分数。要求: (1)使用new动态分配数组。 (2)n和t的值从键盘输入。 (3)定义3个自定义函数:输入数据;计算平均成绩;输出前t个学生的学号和分数。 (4)主函数调用自定义函数。
时间: 2024-06-05 21:06:59 浏览: 24
#include <iostream>
using namespace std;
// 输入数据
void input(int n, int* id, int* score) {
for (int i = 0; i < n; i++) {
cout << "请输入第" << i + 1 << "个学生的学号和成绩:" << endl;
cin >> id[i] >> score[i];
}
}
// 计算平均成绩
double average(int n, int* score) {
int sum = 0;
for (int i = 0; i < n; i++) {
sum += score[i];
}
return double(sum) / n;
}
// 输出前t个学生的学号和分数
void output(int t, int* id, int* score) {
cout << "前" << t << "名学生的学号和分数为:" << endl;
for (int i = 0; i < t; i++) {
cout << "学号:" << id[i] << ",成绩:" << score[i] << endl;
}
}
int main() {
int n, t;
cout << "请输入学生数和要输出的前几名学生:" << endl;
cin >> n >> t;
int* id = new int[n];
int* score = new int[n];
input(n, id, score);
double avg = average(n, score);
cout << "平均成绩为:" << avg << endl;
// 排序,找出前t个学生
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
if (score[i] < score[j]) {
swap(id[i], id[j]);
swap(score[i], score[j]);
}
}
}
output(t, id, score);
delete[] id;
delete[] score;
return 0;
}
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)