根据学号查询成绩和根据姓名查询成绩调用函数两种方法 c语言
时间: 2023-09-07 17:12:01 浏览: 77
使用结构体数组,利用函数实现按学生学号和姓名的查询操作.c
1. 根据学号查询成绩
```
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int id;
int score;
};
void searchById(struct Student s[], int n, int id) {
int i;
for (i = 0; i < n; i++) {
if (s[i].id == id) {
printf("Name: %s\n", s[i].name);
printf("ID: %d\n", s[i].id);
printf("Score: %d\n", s[i].score);
return;
}
}
printf("No record found for ID %d\n", id);
}
int main() {
struct Student students[3] = {{"Alice", 1001, 85}, {"Bob", 1002, 90}, {"Charlie", 1003, 95}};
int id;
printf("Enter ID to search: ");
scanf("%d", &id);
searchById(students, 3, id);
return 0;
}
```
2. 根据姓名查询成绩
```
#include <stdio.h>
#include <string.h>
struct Student {
char name[20];
int id;
int score;
};
void searchByName(struct Student s[], int n, char* name) {
int i;
for (i = 0; i < n; i++) {
if (strcmp(s[i].name, name) == 0) {
printf("Name: %s\n", s[i].name);
printf("ID: %d\n", s[i].id);
printf("Score: %d\n", s[i].score);
return;
}
}
printf("No record found for name %s\n", name);
}
int main() {
struct Student students[3] = {{"Alice", 1001, 85}, {"Bob", 1002, 90}, {"Charlie", 1003, 95}};
char name[20];
printf("Enter name to search: ");
scanf("%s", name);
searchByName(students, 3, name);
return 0;
}
```
阅读全文