c语言结构题来写有n个学生信息(包括学号,姓名,成绩),按学号升序存储在一个结构体数组中,分别用两个函数完成完成按“学号”、“姓名”两个属性进行查找,找出其在数组中是第几个元素。如果不在数组中,则输出“查无此人”。
时间: 2024-05-05 09:20:16 浏览: 91
034 用“结构”统计学生成绩C语言
```c
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 100
// 学生信息结构体
struct Student {
int id;
char name[20];
float score;
};
// 按学号升序排序
void sortById(struct Student students[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (students[j].id > students[j + 1].id) {
temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
// 按姓名升序排序
void sortByName(struct Student students[], int n) {
int i, j;
struct Student temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - 1 - i; j++) {
if (strcmp(students[j].name, students[j + 1].name) > 0) {
temp = students[j];
students[j] = students[j + 1];
students[j + 1] = temp;
}
}
}
}
// 按学号查找
int searchById(struct Student students[], int n, int id) {
int i;
for (i = 0; i < n; i++) {
if (students[i].id == id) {
return i;
}
}
return -1;
}
// 按姓名查找
int searchByName(struct Student students[], int n, char name[]) {
int i;
for (i = 0; i < n; i++) {
if (strcmp(students[i].name, name) == 0) {
return i;
}
}
return -1;
}
int main() {
struct Student students[MAX_SIZE];
int n, i, idIndex, nameIndex, id;
char name[20];
printf("请输入学生人数(不超过100):");
scanf("%d", &n);
printf("请依次输入每个学生的学号、姓名、成绩(用空格隔开):\n");
for (i = 0; i < n; i++) {
scanf("%d %s %f", &students[i].id, students[i].name, &students[i].score);
}
sortById(students, n); // 按学号升序排序
printf("\n按学号升序排序后的学生信息:\n");
for (i = 0; i < n; i++) {
printf("%d %s %.2f\n", students[i].id, students[i].name, students[i].score);
}
printf("\n请输入要查找的学生姓名:");
scanf("%s", name);
nameIndex = searchByName(students, n, name);
if (nameIndex == -1) {
printf("查无此人\n");
} else {
printf("%s 在数组中是第 %d 个元素\n", name, nameIndex + 1);
}
printf("\n请输入要查找的学生学号:");
scanf("%d", &id);
idIndex = searchById(students, n, id);
if (idIndex == -1) {
printf("查无此人\n");
} else {
printf("%d 在数组中是第 %d 个元素\n", id, idIndex + 1);
}
return 0;
}
```
阅读全文