gpt4 book ai didi

c - 如何计算超过 3 个字母的单词数量?

转载 作者:太空宇宙 更新时间:2023-11-03 23:37:01 24 4
gpt4 key购买 nike

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

我尝试执行以下操作:我计算字母直到用户单击空格键。发生这种情况时,我会检查计数器是否大于三。如果是,它会将 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;
}

最佳答案

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

关于c - 如何计算超过 3 个字母的单词数量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57836820/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com