【发布时间】:2013-06-12 07:08:10
【问题描述】:
我想计算一个句子的平均字长。
例如,给定输入abc def ghi,平均字长将为3.0。
该程序有效,但我想忽略单词之间的多余空格。所以,给定以下句子:
abc def
(单词之间有两个空格),平均单词长度计算为2.0而不是3.0。
如何考虑单词之间的多余空格?这些将被忽略,这将在上面的示例中给出3.0 的平均字长,而不是错误计算的2.0。
#include <stdio.h>
#include <conio.h>
int main()
{
char ch,temp;
float avg;
int space = 1,alphbt = 0,k = 0;
printf("Enter a sentence: ");
while((ch = getchar()) != '\n')
{
temp = ch;
if( ch != ' ')
{
alphbt++;
k++; // To ignore spaces before first word!!!
}
else if(ch == ' ' && k != 0)
space++;
}
if (temp == ' ') //To ignore spaces after last word!!!
printf("Average word lenth: %.1f",avg = (float) alphbt/(space-1));
else
printf("Average word lenth: %.1f",avg = (float) alphbt/space);
getch();
}
【问题讨论】:
-
欢迎来到 Stack Overflow!您的问题没有足够的细节,我们无法为您提供帮助。请提供一个 small 示例来说明您正在尝试做什么。还要解释编译和运行示例时的作用以及它与您希望它做的不同之处。
-
查看
strsep(3)。 -
@Code-Guru;我已经在我的问题中给出了详细信息和示例。
标签: c