2011-09-01 76 views
1

嗨,大家好,我只是使用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給我一個答案...

回答

8

嘗試使用大括號和c = getchar()需要括號。

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

的錯誤是在這裏:

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

2

解決辦法:

變化而(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