文の平均語長を計算したい。
たとえば、入力が与えられabc def ghi
た場合、平均語長は になります3.0
。
プログラムは動作しますが、単語間の余分なスペースを無視したいです。したがって、次の文が与えられます。
abc def
(単語間に 2 つのスペース)、平均単語長は ではなく と計算され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();
}