簡體   English   中英

如何計算超過3個字母的單詞數量?

[英]How to count the amount of words with more than 3 letters?

我正在嘗試編寫一個程序來計算超過三個字母的單詞數量。 當輸入一個句點時,程序必須結束。 我的代碼有效,但它無法計算第一個單詞,因此,如果我輸入超過三個字母的三個單詞,則輸出為兩個。

我嘗試執行以下操作:我計算字母,直到用戶單擊空格鍵。 發生這種情況時,我會檢查計數器是否大於 3。 如果是,則將 counterLargerThanThree 增加 1。 這會持續運行,直到用戶輸入一個句點。 當用戶輸入句點時,程序結束。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    int cont = 0, aux , counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");

    c = getchar();

    while(c != '.')
    {
        aux = c;
        c = getchar();
        cont++;

        if(aux == ' ')
        {
            if(cont>3)
            {
                counterLargerThanThree++;
            }

            cont = 0;
        }
    }

    printf("%i \n",counterLargerThanThree);


    system("pause");
    return 0;
}

在您輸入的末尾(即遇到一個點時), while循環將被跳過,如果最后一個單詞的長度超過三個字符,您將永遠沒有機會計算該單詞。

試試這個:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char c;
    int cont = 0, counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");

    do
    {
        c = getchar();
        if (c != ' ' && c != '.')
        {
            ++cont;
        }
        else
        {
            if (cont > 3)
            {
                counterLargerThanThree++;
            }
            cont = 0;
        }
    }
    while (c != '.');

    printf("%i \n", counterLargerThanThree);


    system("pause");
    return 0;
}

您沒有將最后一個單詞視為句點字符. 即使字長> 3,你也會打破循環。 嘗試這樣的事情。

#include<stdio.h>
#include <stdlib.h>

int main()
{
    int c;
    int cont = 0, aux , counterLargerThanThree = 0;
    printf("Enter a phrase that ends with a period:\n");


    while(1)
    {
        c = getchar();
        cont++;

        if(c == ' ' || c=='.')
        {
            if(cont>3)
            {
                counterLargerThanThree++;
            }

            cont = 0;
        }
        if(c=='.'){
            break;
        }
    }


    printf("%i \n",counterLargerThanThree);


    system("pause");
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM