c语言结构体来写有n个学生信息(包括学号,姓名,成绩),按学号升序存储在一个结构体数组中,分别用两个函数完成完成按“学号”、“姓名”两个属性进行查找,找出其在数组中是第几个元素。如果不在数组中,则输出“查无此人”。
时间: 2024-05-02 12:19:23 浏览: 9
```c
#include <stdio.h>
#include <string.h>
#define MAX_N 100
typedef struct {
int id;
char name[20];
int score;
} Student;
int search_by_id(Student students[], int n, int target_id);
int search_by_name(Student students[], int n, char target_name[]);
int main() {
Student students[MAX_N];
int n;
printf("Please input the number of students (<= %d): ", MAX_N);
scanf("%d", &n);
printf("Please input the information of %d students:\n", n);
for (int i = 0; i < n; i++) {
printf("No.%d: ", i+1);
scanf("%d %s %d", &students[i].id, students[i].name, &students[i].score);
}
int choice;
printf("Please choose the search method:\n");
printf("1. Search by id\n");
printf("2. Search by name\n");
scanf("%d", &choice);
switch (choice) {
case 1: {
int target_id;
printf("Please input the target id: ");
scanf("%d", &target_id);
int index = search_by_id(students, n, target_id);
if (index >= 0) {
printf("%s's id is %d, score is %d, located at index %d.\n",
students[index].name, students[index].id, students[index].score, index);
} else {
printf("查无此人。\n");
}
break;
}
case 2: {
char target_name[20];
printf("Please input the target name: ");
scanf("%s", target_name);
int index = search_by_name(students, n, target_name);
if (index >= 0) {
printf("%s's id is %d, score is %d, located at index %d.\n",
students[index].name, students[index].id, students[index].score, index);
} else {
printf("查无此人。\n");
}
break;
}
default: {
printf("无效的选项。\n");
break;
}
}
return 0;
}
int search_by_id(Student students[], int n, int target_id) {
int left = 0, right = n-1;
while (left <= right) {
int mid = (left + right) / 2;
if (students[mid].id == target_id) {
return mid;
} else if (students[mid].id < target_id) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int search_by_name(Student students[], int n, char target_name[]) {
for (int i = 0; i < n; i++) {
if (strcmp(students[i].name, target_name) == 0) {
return i;
}
}
return -1;
}
```