9.编写程序:有3个学生,每个学生有4门课程的成绩。要求用户输入学生 序号以后,能输出该学生的全部成绩。用指针函数来实现 学...
时间: 2024-02-12 13:07:22 浏览: 54
以下是使用指针函数实现的程序:
```c++
#include <iostream>
using namespace std;
// 定义学生结构体
struct Student {
int id; // 学生序号
int scores[4]; // 成绩数组
};
// 定义指针函数,返回指向学生的指针
Student* getStudent(int id, Student* students, int size) {
for (int i = 0; i < size; i++) {
if (students[i].id == id) {
return &students[i];
}
}
return NULL;
}
int main() {
// 初始化学生信息
Student students[3] = {
{1, {90, 80, 70, 85}},
{2, {75, 82, 92, 88}},
{3, {88, 92, 80, 78}}
};
// 输入学生序号
int id;
cout << "请输入学生序号:";
cin >> id;
// 调用指针函数获取学生指针
Student* student = getStudent(id, students, 3);
// 输出学生全部成绩
if (student != NULL) {
cout << "学生" << student->id << "的成绩为:\n";
for (int i = 0; i < 4; i++) {
cout << "科目" << i+1 << "成绩:" << student->scores[i] << endl;
}
} else {
cout << "找不到该学生!" << endl;
}
return 0;
}
```
程序先定义了一个学生结构体,包含学生序号和成绩数组。然后定义了一个指针函数 `getStudent`,接收学生序号、学生数组和数组大小作为参数,返回指向学生的指针。在 `main` 函数中,首先初始化了3个学生的信息,然后要求用户输入学生序号,并调用 `getStudent` 函数获取指向该学生的指针。如果指针不为空,则输出该学生的全部成绩;否则输出找不到该学生的信息。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)