【问题标题】:How to count the amount of words with more than 3 letters?如何计算超过 3 个字母的单词数量?
【发布时间】:2019-09-07 19:22:23
【问题描述】:

我正在尝试编写一个程序来计算超过三个字母的单词的数量。当输入句点时,程序必须结束。我的代码有效,但它无法计算第一个单词,所以,如果我输入三个超过三个字母的单词,则输出为 2。

我尝试执行以下操作:我计算字母直到用户单击空格键。发生这种情况时,我会检查计数器是否大于三。如果是,则将 counterLargerThanThree 加一。这会持续运行,直到用户输入一个句点。当用户输入句点时,程序结束。

#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;
}

【问题讨论】:

  • .句点字符出现时,即使字长>3,你也不会计算最后一个单词。

标签: c char


【解决方案1】:

在输入结束时(即遇到点时),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;
}

【讨论】:

    【解决方案2】:

    当句点字符. 出现时,即使单词长度>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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-12-11
      • 2022-06-21
      • 1970-01-01
      • 2023-02-21
      • 2016-08-13
      • 2015-11-18
      • 2012-10-08
      相关资源
      最近更新 更多