void SearchByName(struct student stu[], int n, char *name) { int left = 0, right = n - 1; while (left <= right) { int mid = (left + right) / 2; if (strcmp(stu[mid].name, name) == 0) { return mid; } else if (strcmp(stu[mid].name, name) > 0) { right = mid - 1; } else { left = mid + 1; } } return -1; } scanf("%s",name); int index; index=SearchByName(stu, n, name); if(index!=-1) { printf("查询结果:\n%s %s %d\n", stu[index].name, stu[index].id, stu[index].room); } else { printf("没有找到该学生\n");如何修改
时间: 2024-02-14 22:10:28 浏览: 77
这段代码本身有一些问题,因为函数的返回类型是void,但是在函数内部又使用了return语句。应该将函数的返回类型修改为int,以便正确返回查找结果。此外,在找到目标学生时应该直接返回mid,而不是返回函数值为mid。修改后的代码如下:
```
int SearchByName(struct student stu[], int n, char *name) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = (left + right) / 2;
if (strcmp(stu[mid].name, name) == 0) {
return mid;
} else if (strcmp(stu[mid].name, name) > 0) {
right = mid - 1;
} else {
left = mid + 1;
}
}
return -1;
}
// 在主函数中的调用代码
scanf("%s",name);
int index = SearchByName(stu, n, name);
if (index != -1) {
printf("查询结果:\n%s %s %d\n", stu[index].name, stu[index].id, stu[index].room);
} else {
printf("没有找到该学生\n");
}
```
阅读全文