我正在试着写一个程序来计算超过三个字母的单词的数量。当输入句号时,程序必须结束。我的代码可以工作,但它不能计算第一个单词,因此,如果我输入三个字母以上的三个单词,则输出为两个。
我试着这样做:我数字母,直到用户点击空格键。当发生这种情况时,我检查计数器是否大于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;
}发布于 2019-09-08 03:44:22
在输入结束时(即遇到一个点时),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;
}发布于 2019-09-08 03:47:19
你没有计算最后一个单词,因为当句点字符.出现时,即使单词length>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;
}https://stackoverflow.com/questions/57836820
复制相似问题