帮我分析这C程序:输出若干人员的姓名及电稿号码,以字符#结束输入,然后输入姓名,查找该人的电话号码?

来源:百度知道 编辑:UC知道 时间:2024/04/30 13:59:03
这是我自己写的,但我总感觉写的不好,感觉很乱,如果,要你写,你会有什么简洁的程序吗?你会怎么写啦,谢谢!
#include <stdio.h>
#include <string.h>
#define MAX 100
int input(void);
void search(char *x,int n);
struct telephone {
char name[10];
char telno[20];}data[MAX];
void main()
{int n;
char na[10];
n=input();
printf("input the name you want search:");
gets(na);
search(na,n);
getch();
}
int input(void)
{int i=0;
for(;;) {
printf("input the name:");
gets(data[i].name);
if(strcmp(data[i].name,"#")==0) break;
printf("input the telephone:");
gets(data[i].telno);
i++;
}
return i;
}
void search(char *x,int n)/*这里我觉的写的不好*/
{int i;
for(i=0;strcmp(data[i].name,"#")!=0;i++)
if(strcmp(data[i].name,x)==0)
{printf("the number is %s.\n",data[i].telno);break;}
if(i>=n) printf("sorry not found.\n

我简单说说我初步印象吧,说得不好请多多包含。

第一,我觉得你的变量名定义没有意义,我觉得最好是用有意义的单词,这样可以加强程序的可读性。
第二,
for(;;) {
printf("input the name:");
gets(data[i].name);
if(strcmp(data[i].name,"#")==0) break;
printf("input the telephone:");
gets(data[i].telno);
i++;
}
for(;;) 一般我们用while(1)或while(true),这样清晰些。

3.search 最好不要返回为空,应该返回具体的值。
显示的部分,可以在main函数中书写,这样做,可以提高search的复用性,在其他程序中,还是可以使用search来实现其功能。或者修改起来也方便。

入行这么久最大的体会就是只有学生才有那么多时间斟酌程序的时间空间效率问题,工作的程序员多是赶工实现功能就算了,有些还迟迟实现不了一拖再拖...当然不排除有高手的,哈哈

效率方面不说
第一,安全性方面,gets和strcmp都是不安全的函数~~已经有新的函数代替了它们,所以以后还是尽量少用!
第二,写程序刻加注释,各种变量的作用,函数的作用及参数
第三,类似你写的search函数这种需要调用它的函数知道结果的,请一定加上返回值,这样才能更好的实现函数之间的紧密性