寻找程序的错误,并改正:#include <stdio.h> #include <string.h> struct Workers { int num; char name[20]; }; void input(struct Workers a[]) {int i; for(i=0;i<10;i++) scanf("%d %s",&a[i].num,a[i].name); } void sort(struct Workers a[]) {int i,j; char b[20]; struct Workers temp; for(i=0;i<9;i++) for(j=0;j<9-i;j++) {if(a[j].num>a[j+1].num) {temp=a[j];a[j]=a[j+1];a[j+1]=temp; strcpy(b,a[j].name);strcpy(a[j].name,a[j+1].name);strcpy(a[j+1].name,b);} } void search(struct Workers worker[],int n) {int low = 0, high = 9, mid; while (low <= high) {mid = (low + high) / 2; if (worker[mid].num == n) { printf("职工号为%d的职工姓名为%s。\n", n, worker[mid].name); return; } else if (worker[mid].num > n) {high = mid - 1; } else { low = mid + 1; } } printf("无法找到职工号为%d的职工。\n", n); } int main() {int n=0; input(worker); sort(worker); printf("输入你要查找的工号:"); scanf("%d",&n); search(worker); return 0; }
时间: 2024-03-21 18:41:11 浏览: 52
第9章 指针-课堂研讨案例9-1-寻找语法错误、改正程序.c
在 main 函数中,调用了 search 函数时,只传入了一个参数,但是 search 函数需要两个参数。正确的调用方式应该是:search(worker, n)。
另外,在程序开头定义了一个结构体 Workers,但是在 main 函数中没有定义结构体数组 worker,应该在 main 函数中定义一个结构体数组并传入函数中进行操作。完整代码如下:
```
#include <stdio.h>
#include <string.h>
struct Workers {
int num;
char name[20];
};
void input(struct Workers a[]) {
int i;
for(i=0; i<10; i++)
scanf("%d %s", &a[i].num, a[i].name);
}
void sort(struct Workers a[]) {
int i,j;
char b[20];
struct Workers temp;
for(i=0; i<9; i++)
for(j=0; j<9-i; j++) {
if(a[j].num > a[j+1].num) {
temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
strcpy(b,a[j].name);
strcpy(a[j].name,a[j+1].name);
strcpy(a[j+1].name,b);
}
}
}
void search(struct Workers worker[], int n) {
int low = 0, high = 9, mid;
while (low <= high) {
mid = (low + high) / 2;
if (worker[mid].num == n) {
printf("职工号为%d的职工姓名为%s。\n", n, worker[mid].name);
return;
} else if (worker[mid].num > n) {
high = mid - 1;
} else {
low = mid + 1;
}
}
printf("无法找到职工号为%d的职工。\n", n);
}
int main() {
struct Workers worker[10];
int n=0;
input(worker);
sort(worker);
printf("输入你要查找的工号:");
scanf("%d",&n);
search(worker, n);
return 0;
}
```
阅读全文