我编写一个判断一学生是否属于一班级的程序,如下:
#define MAX 5
#define LEN 10
main()
{
int i;
char name[LEN];
static char list [MAX][LEN]={"Zhang","Wang","Li","Tan","Ling"};
printf("Enter your name:");
gets(name);
for(i=0;i<MAX;i++)
if(strcmp(list[i],name)==0)
printf("%s is in our class\n",name);
else
printf("%s is not in our class\n",name);
}
编译没有错误,但在执行时,结果显示:
Enter your name: Zhang
Zhang is in our class
Zhang is not in our class
Zhang is not in our class
Zhang is not in our class
Zhang is not in our class
Press any key to continue
请问这是什么原因?
书上的原程序是:
#define MAX 5
#define LEN 10
main()
{
int i,flag=0;
char name[LEN];
static char list [MAX][LEN]={"Zhang","Wang","Li","Tan","Ling"};
printf("Enter your name:");
gets(name);
for(i=0;i<MAX;i++)
if(strcmp(list[i],name)==0)flag==1;
if(flag==1)
printf("%s is in our class\n",name);
else
printf("%s is not in our class\n",name);
}
和我自己编写的差别是多加了flag,请问这个flag是什么作用?是编写strcmp这个比较功能的函数时必须使用的吗?
元芳怎么了