用c++实现下面问题:题目描述 建立一个对象数组,内放5个学生的数据(学号、成绩),设立一个函数max,用指向对象的指针做函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号及最高成绩。 输入格式 5个学生的学号和成绩 输出格式 成绩最高者的学号和成绩 样例输入content_copy 101 78.5 102 85.5 103 98.5 104 100 105 95.5 样例输出content_copy 104 100
时间: 2024-03-07 20:50:17 浏览: 33
以下是用C++实现的代码:
```c++
#include <iostream>
using namespace std;
class Student {
public:
int id;
float score;
};
Student stu[5];
void max(Student *p) {
int max_index = 0;
for (int i = 1; i < 5; i++) {
if (p[i].score > p[max_index].score) {
max_index = i;
}
}
cout << p[max_index].id << " " << p[max_index].score << endl;
}
int main() {
for (int i = 0; i < 5; i++) {
cin >> stu[i].id >> stu[i].score;
}
max(stu);
return 0;
}
```
使用对象数组存储学生信息,定义max函数遍历指向学生对象的指针,找到成绩最高的学生并输出其学号和成绩。在main函数中输入学生信息,调用max函数即可实现题目要求。
相关问题
建立一个对象数组,内放5个学生的学号和成绩,用指针指向数组首元素输出全部学生的数据
可以使用以下代码建立对象数组并输出全部学生的数据:
```c++
#include <iostream>
using namespace std;
class Student {
public:
int id;
int score;
};
int main() {
Student students[5] = {{1, 90}, {2, 85}, {3, 92}, {4, 88}, {5, 95}};
Student* p = students;
for (int i = 0; i < 5; i++) {
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p++;
}
return 0;
}
```
输出结果为:
```
学号:1,成绩:90
学号:2,成绩:85
学号:3,成绩:92
学号:4,成绩:88
学号:5,成绩:95
```
建立一个对象数组,内放5个学生的学号和成绩,用指针指向数组的首元素,输出第1,3,5学生的数据。用C++实现
下面是用C++实现的代码:
```cpp
#include <iostream>
using namespace std;
struct Student {
int id; // 学号
int score; // 成绩
};
int main() {
Student students[5] = {
{1001, 85},
{1002, 92},
{1003, 78},
{1004, 90},
{1005, 88}
}; // 定义并初始化学生数组
Student* p = students; // 使用指针指向数组的首元素
cout << "第1个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p += 2; // 指向第3个学生的数据
cout << "第3个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
p += 2; // 指向第5个学生的数据
cout << "第5个学生的数据:" << endl;
cout << "学号:" << p->id << ",成绩:" << p->score << endl;
return 0;
}
```
输出结果:
```
第1个学生的数据:
学号:1001,成绩:85
第3个学生的数据:
学号:1003,成绩:78
第5个学生的数据:
学号:1005,成绩:88
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)