使用指针和函数的方式,查询自己的成绩。从键盘输入3位学生4门课程的成绩,输入学号,即可查询到自己各门课程的成绩。
时间: 2024-03-17 17:46:28 浏览: 21
好的,可以的。下面是一个简单的程序,实现了你的要求:
```c
#include <stdio.h>
// 定义学生结构体
struct student {
int id; // 学号
float scores[4]; // 成绩数组
};
// 传入学生数组和学号,返回对应学生的指针
struct student* find_student(struct student arr[], int id) {
for (int i = 0; i < 3; i++) {
if (arr[i].id == id) {
return &arr[i];
}
}
return NULL;
}
// 输出学生的成绩
void print_scores(struct student* s) {
if (s == NULL) {
printf("学生不存在!\n");
return;
}
printf("学号:%d\n", s->id);
printf("成绩:");
for (int i = 0; i < 4; i++) {
printf("%.1f ", s->scores[i]);
}
printf("\n");
}
int main() {
struct student arr[3];
// 输入学生信息
for (int i = 0; i < 3; i++) {
printf("请输入第%d个学生的学号和成绩(四门课):\n", i+1);
scanf("%d", &arr[i].id);
for (int j = 0; j < 4; j++) {
scanf("%f", &arr[i].scores[j]);
}
}
// 输入要查询的学号
int id;
printf("请输入要查询的学号:\n");
scanf("%d", &id);
// 查询并输出成绩
struct student* s = find_student(arr, id);
print_scores(s);
return 0;
}
```
这个程序定义了一个名为 `student` 的结构体,包含了学号和四门课程成绩。然后定义了两个函数,`find_student` 用于查询对应学号的学生,`print_scores` 用于输出学生的成绩。
在 `main` 函数中,先输入所有学生的信息,然后输入要查询的学号,最后调用上面两个函数进行查询和输出。注意,如果查找不到学生,需要输出提示信息。
希望这个程序能够帮助到你!
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://img-home.csdnimg.cn/images/20210720083646.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)