我的代码没有按预期工作。我创建了一个数组来跟踪字长。对于输入“测试测试测试”,我想输出数组:[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]);
}
我究竟做错了什么?