建立一个对象数组,内存放10个学生的数据,建立一个函数max,用指向对象的指针做函数参数,在max函数中找出10个学生中成绩最高者,并输出其学号。
时间: 2023-05-23 12:02:44 浏览: 83
可以这样实现:
```
#include <iostream>
using namespace std;
class Student {
public:
string id;
float score;
};
void max(Student* students, int len) {
int maxIndex = 0;
for (int i = 1; i < len; i++) {
if (students[i].score > students[maxIndex].score) {
maxIndex = i;
}
}
cout << "最高分学生的学号为:" << students[maxIndex].id << endl;
}
int main() {
Student students[10];
for (int i = 0; i < 10; i++) {
cout << "请输入第" << i+1 << "个学生的学号和成绩:";
cin >> students[i].id >> students[i].score;
}
max(students, 10);
return 0;
}
```
使用对象数组存储10个学生的信息,max函数接收一个指向Student对象的指针以及数组长度,遍历整个数组,找出成绩最高的学生,并输出其学号。在main函数中输入学生的信息,并调用max函数进行处理。
相关问题
.建立一个对象数组,内放5个学生的数据(学生、成绩),设立一个函数max,用指向对象的指针作函数参数,在max函数中找出5个学生中成绩最高者,并输出其学号。
```cpp
#include <iostream>
using namespace std;
class Student {
public:
string name;
int score;
};
void max(Student* arr, int len) {
int maxScore = arr[0].score;
int maxIndex = 0;
for (int i = 1; i < len; i++) {
if (arr[i].score > maxScore) {
maxScore = arr[i].score;
maxIndex = i;
}
}
cout << "The student with the highest score is: " << arr[maxIndex].name << endl;
}
int main() {
Student students[5] = { {"Tom", 80}, {"Jack", 90}, {"Alice", 75}, {"Bob", 85}, {"Lucy", 95} };
max(students, 5);
return 0;
}
```
用c++编写 建立一个对象数组,内放五个学生的数据(学号、成绩),设立一个函数max,用指向对象的指针做函数参数,在max参数中找出五个学生中成绩最高值,并输出其学号。
以下是代码实现:
```c
#include <stdio.h>
struct Student {
int id;
int score;
};
int max(struct Student *students, int n) {
int maxScore = students[0].score;
int maxId = students[0].id;
for (int i = 1; i < n; i++) {
if (students[i].score > maxScore) {
maxScore = students[i].score;
maxId = students[i].id;
}
}
return maxId;
}
int main() {
struct Student students[5] = {
{1, 80},
{2, 90},
{3, 70},
{4, 85},
{5, 95}
};
int maxId = max(students, 5);
printf("最高分的学生学号为:%d\n", maxId);
return 0;
}
```
输出结果为:
```
最高分的学生学号为:5
```
这里我们定义了一个 `Student` 结构体,包含学号和成绩两个属性。然后定义了一个 `max` 函数,用于找出学生数组中成绩最高的学生的学号。在 `main` 函数中,我们创建了一个包含五个学生数据的数组,并调用 `max` 函数来获取最高分的学生的学号。最后输出结果即可。
阅读全文
相关推荐
![](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)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)