错误的C程序输出没有错误

问题描述:

嗨,大家好,我只是使用Notepad ++和Cygwin在C中使用这个小程序。因此,代码如下:错误的C程序输出没有错误

#include <stdio.h> 

int main() 
{ 
     int c, i, countLetters, countWords; 
     int arr[30]; 

     countLetters = countWords = 0; 
     for(i = 0; i < 30; ++i) 
      arr[i] = 0; 

     while(c = getchar() != EOF) 
       if(c >= '0' && c <= '9') 
        ++arr[c - '0']; 

       else if (c == ' ' || c == '\n' || c == '\t') 
        ++countWords; 

       else 
        ++countLetters; 

     printf("countWords = %d, countLetters = %d\n", 
     countWords, countLetters); 
} 

但代替数数的话则计算单词字母和打印出来的字母和单词= 0 ...我在哪里错了,因为连我的老师couldn`t给我一个答案...

尝试使用大括号和c = getchar()需要括号。

while((c = getchar()) != EOF) { 
    ^   ^
    /* Stuff. */ 
} 

的错误是在这里:

while(c = getchar() != EOF) 

您需要封闭分配括号,就像这样:

while((c = getchar()) != EOF) /*** assign char to c and test if it's EOF **/ 

否则,它被解释为:

while(c = (getchar() != EOF)) /** WRONG! ***/ 

即c对于每个字符读取1 il文件的结尾。

+1

+1不错,清楚的解释。 – razlebe

解决办法:

变化而(C =的getchar()= EOF!),以同时((C =的getchar())= EOF!)

原因是:

!=具有更高的优先级比 =

因此,

的getchar()!= EOF

评估为假,并从而成为

而(C = 1)==>而(0)。

因此,循环得到迭代c = 1,你的输入是什么。 (EOF除外)。

在这种情况下,你的表情总是计算是错误的。

以来,

如果(C> = '0' & &ç< = '9')是,如果(1> = 48 & = 57)和它总是假的。

此外,

否则如果(C == '' ||ç== '\ n' ||ç== '\ T')

将评估,以是假的。

因此,其他部分countLetters ++将被执行所有输入!

由此导致的情况。

+0

+1解释*为什么*括号是必需的。 – JeremyP