首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C语言 >

帮忙看看这句switch语句异常

2012-08-16 
帮忙看看这句switch语句错误?C/C++ code#includestdio.h#includestring.h#includeconio.h#includes

帮忙看看这句switch语句错误?

C/C++ code
#include<stdio.h>#include<string.h>#include<conio.h>#include<stdlib.h>#include<windows.h>main(){    char *q1="what is your name";    char *a1="I am lion";    char *q2="how are you";    char *a2="I am fine,thx!";    char *q3="what is the weather like today";    char *a3="the day was very hot today!";    char *p="Sorry! I can't undersdant what your mean!";    char w1[100];    while(true)    {        puts("Lion: what can I do for you?");        printf("You: ");        gets(w1);        switch(w1)        {                case (strcmp(q1,w1)==0):Sleep(800);                    printf("lion:%s\n",a3);                system("e:\\a1.vbs"); break;                case (strcmp(q2,w1)==0):Sleep(800);                    printf("lion:%s\n",a2);                system("e:\\a1.vbs"); break;                            case (strcmp(q3,w1)==0):Sleep(800);                    printf("lion:%s\n",a3);                system("e:\\a3.vbs"); break;                                default: Sleep(800);                    printf("\nlion:%s",p);                system("e:\\p.vbs");break;        }        }}


[解决办法]
strcmp(q1,w1)==0返回的是逻辑值,1或0
你写的switch结构相当于
switch(w1)
{
 case 1/0:
 case 1/0:
 ...
}

这个是不符合逻辑的,你这种情况判断的条件比较复杂,用switch不好
用if else比较好
当然再优化一下,你可以考虑将q1,q2,q3放在一个数组中,a1,a2,a3放另外一个数组
然后用for循环来写。

热点排行