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]);
}

私は何を間違っていますか?

4

1 に答える 1

1

変更をコンパイルするのを忘れていませんか? おそらく、いくつかのコードを変更し、たまたま以前のビルドを見ていました。

于 2013-08-01T21:18:38.947 に答える