魔法王座六翼圣使:C语言编程高手给看看这个程序错在哪里

来源:百度文库 编辑:高校问答 时间:2024/05/04 05:22:19
#include "stdio.h"
main()
{
char string[81];
int i,num=0,word=0;
char c;
gets (string);
for(i=0;(c=string[i])!='\0';i++)
if(c=='')word=0;
else if(word==0)
{
word=1;
num++;
}
printf("There are %d words in the line\n",num);
}

为什么我在输入 I am a boy. 回车 然后查看结果,提示 There are 1 words in the line.
不对啊,应该是4个啊,怎么回事,这个程序是我从书上找到的,应该不会错啊,那到底是哪里不对啊

逻辑错误

下面这一段
if(c=='')word=0;
else if(word==0)
{
word=1;
num++;
}

中的else if(word==0)
修改为else就可以了

因为当执行一次后word=1
那么word绝对不会==0
所以后面的就被跳过了
以下是修改后的程序

#include "stdio.h"
main()
{
char string[81];
int i,num=0,word=0;
char c;
gets (string);
for(i=0;(c=string[i])!='\0';i++)
if(c=='')word=0;
else
{
word=1;
num++;
}
printf("There are %d words in the line\n",num);
}