0

countWords以下のプログラムで関数がどのように機能するかを理解するために、いくつかの助けが必要です。

スティーブン・コチャンが書いた「Programming in C」ですべて説明されていますが、関数の「lookingForWord」と「++ wordCount」に関しては、どのように機能するのかわかりませんでしたcountWords

#include <stdio.h>
#include <stdbool.h>

//function to determine if a character is alphabetic
bool alphabetic (const char c)
{
    if ( (c >= 'a' && c <= 'z') || ( c >= 'A' && c <= 'Z'))     
        return true;
    else
        return false;
}

// function to count the number of words in a string
int countWords ( const char string[])
{
    int i, wordCount = 0;
    bool lookingForWord = true, alphabetic ( const char c);

    for ( i = 0; string[i] != '\0'; ++i)
        if (alphabetic(string[i]) )
        {
            if ( lookingForWord )
            {
                ++wordCount;
                lookingForWord = false;
            }
        }
        else
            lookingForWord = true;

    return wordCount;
}

int main ( void)
{
    const char text1[] = {"Well, here goes."};
    const char text2[] = { "And here we go... again"};
    int countWords (const char string[]);

    printf( " %s - words = %i\n", text1, countWords (text1));
    printf( " %s - words = %i\n", text2, countWords (text2));

    return 0;
}
4

2 に答える 2

5

関数は単語の最初の文字をカウントし、残りの文字をスキップして(に設定lookingForWordすることによりfalse)、文字以外の文字にヒットするlookingForWordとtrueにリセットされ、次の文字としてカウントされます。新しい言葉。

したがって、この関数はすべてを、falseの文字で区切られた個別の単語としてカウントしalphabetic()ます(したがって、「しない」と「時」はそれぞれ2つの単語としてカウントされます)。

于 2012-03-12T23:08:10.627 に答える
0
  1. アルゴリズムはlookingForWordtrue に初期化することから始まります (常に単語の検索を開始するため)。
  2. 次に、センチネル値 '\0' が見つかるまでループします。
  3. charat 位置iがアルファベットかどうかをチェックします
  4. はいの場合、新しい単語が見つかったので、値を増やして falsewordCountに設定しますlookingForWord
  5. is true but is falseの増加なしにループし続けwordCountますalphabetic(string[i])lookingForWord
  6. アルファベット以外の文字に遭遇すると、wordCountfalse に設定するので、true の次のループでalphabetic(string[i])値を増やします。wordCount

私が少し確信が持てないのは、このコードの作成者が次の行に入れている理由です。

bool lookingForWord = true, alphabetic ( const char c);

以下を使用してコードをコンパイルしました。

bool lookingForWord = true; //,alphabetic (const char c);

しかし、結果は同じままでした。

于 2012-03-12T23:27:56.907 に答える