1
我的代碼無法按預期工作。我創建一個數組來跟蹤字長。對於輸入「測試測試」,我想輸出數組:[0 0 0 3 0 0 0 0 0 0]。打印數組字長不能按預期方式工作
我的實際輸出爲[0 0 0 0 2 0 0 0 0 0]
這裏是我的代碼:
#include <stdio.h>
main()
{
int c, i, characters;
int word_lengths [10];
characters = 0; //word character count
for (i = 0; i <10; ++i)
word_lengths[i] = 0; //initialize histogram
while ((c = getchar()) != EOF)
{
if (c == ' ' || c == '\t' || c == '\n'){ //if blank/tab/new line, reset the character count for new word
if (characters != 0){ //end of word, increment word length count
++word_lengths[characters-1]; //array index starts at 0
}
characters = 0;
}
else { //inside a word: increment character count
++characters;
}
}
++word_lengths[characters-1];
for (i = 0; i <10; ++i)
printf("Length of words = %d\n", word_lengths[i]);
}
我在做什麼錯?
因爲代碼審查是在標題,也許你想發佈此[代碼評論](http://codereview.stackexchange.com/) – aaronman
爲什麼你預增加一切? –
@Scotty因爲預先遞增比後遞增更有效率。 「你在做什麼錯了?」幾件事。這裏有一個:當你打到20個字時,會發生什麼? Supercalifragilistic。 –