(1)输入两个学生的学号、姓名和成绩,输出成绩较高学生的学号、姓名和成绩. (2)用指针方式实现上面的程序。指针
时间: 2025-01-03 19:44:37 浏览: 5
(1)这是一个简单的编程任务,可以使用结构体或者自定义的对象来存储学生信息,并通过比较分数来找出最高分的学生。以下是使用C++语言的一个示例:
```cpp
#include <iostream>
using namespace std;
struct Student {
int id;
string name;
int score;
};
void find_highest_score(Student *students, int num_students) {
Student highest_student = students[0];
for (int i = 1; i < num_students; i++) {
if (students[i].score > highest_student.score) {
highest_student = students[i];
}
}
cout << "学号: " << highest_student.id << ", 姓名: " << highest_student.name << ", 成绩: " << highest_student.score << endl;
}
int main() {
Student students[] = { {1, "小明", 95}, {2, "小红", 98} };
int num_students = sizeof(students) / sizeof(students[0]);
find_highest_score(students, num_students);
return 0;
}
```
(2)如果要用指针来实现同样的功能,你可以创建一个指向`Student`类型的指针数组,并遍历这个数组找到最高分的学生。这里是一个指针版本的例子:
```cpp
#include <iostream>
using namespace std;
struct Student {
int id;
string name;
int score;
};
void find_highest_score(Student *students, int num_students) {
Student *highest_student = &students[0];
for (int i = 1; i < num_students; i++) {
if (students[i].score > highest_student->score) {
highest_student = &students[i];
}
}
cout << "学号: " << highest_student->id << ", 姓名: " << highest_student->name << ", 成绩: " << highest_student->score << endl;
}
int main() {
Student *students = new Student[2] {{1, "小明", 95}, {2, "小红", 98}};
int num_students = 2; // 数组大小
find_highest_score(students, num_students);
delete[] students; // 释放内存
return 0;
}
```
阅读全文