gpt4 book ai didi

c - 一个句子的平均字长

转载 作者:太空宇宙 更新时间:2023-11-04 05:19:38 25 4
gpt4 key购买 nike

我想计算一个句子的平均字长。

例如,给定输入 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();
}

最佳答案

计数逻辑有误。此代码似乎可以正确处理前导和尾随空格,以及单词之间的多个空格等。注意 int ch; 的使用以便代码可以准确检查 EOF(getchar() 返回 int)。

#include <stdio.h>
#include <stdbool.h>

int main(void)
{
int ch;
int numWords = 0;
int numLetters = 0;
bool prevWasASpace = true; //spaces at beginning are ignored

printf("Enter a sentence: ");
while ((ch = getchar()) != EOF && ch != '\n')
{
if (ch == ' ')
prevWasASpace = true;
else
{
if (prevWasASpace)
numWords++;
prevWasASpace = false;
numLetters++;
}
}

if (numWords > 0)
{
double avg = numLetters / (float)(numWords);
printf("Average word length: %.1f (C = %d, N = %d)\n", avg, numLetters, numWords);
}
else
printf("You didn't enter any words\n");
return 0;
}

各种示例运行,使用 #指示 Return 被击中的位置。

Enter a sentence: A human in Algiers#
Average word length: 3.8 (C = 15, N = 4)

Enter a sentence: A human in Algiers #
Average word length: 3.8 (C = 15, N = 4)

Enter a sentence: A human in Algiers #
Average word length: 3.8 (C = 15, N = 4)

Enter a sentence: #
You didn't enter any words

Enter a sentence: A human in AlgiersAverage word length: 3.8 (C = 15, N = 4)

Enter a sentence: You didn't enter any words

在最后一个例子中,我输入了两次 Control-D(第一次将“A human in Algiers”刷新到程序中,第二次给出 EOF),然后在最后一个例子。请注意,此代码将制表符计为“非空格”;你需要 #include <ctype.h>if (isspace(ch)) (或 if (isblank(ch)) )代替 if (ch == ' ')更好地处理制表符。


getchar()返回 int

I am confused why you have used int ch and EOF!

这个答案有几个部分。

  1. 使用int ch的第一个原因是getchar()函数返回 int .它可以返回任何有效字符加上一个单独的值EOF;因此,它的返回值不能是 char任何类型的,因为它必须返回比 char 所能容纳的更多的值.它实际上返回一个 int .

  2. 为什么重要?假设来自 getchar() 的值分配给 char ch .现在,对于大多数角色,大多数时候,它都可以正常工作。但是,会发生以下两种情况之一。如果普通 char是有符号类型,有效字符(通常是 ÿ、y-umlaut、0xFF、正式的 Unicode U+00FF、带分音符的拉丁文小写字母 Y)被错误识别为 EOF。或者,如果是普通的 char是无符号类型,那么你永远不会检测到 EOF。

  3. 为什么检测 EOF 很重要?因为您的输入代码可以在您不期望的时候获得 EOF。如果你的循环是:

    int ch;

    while ((ch = getchar()) != '\n')
    ...

    并且输入到达 EOF,程序将花费很长时间做无用的事情。 getchar()函数会重复返回 EOF,而 EOF 不是 '\n' ,所以循环会再试一次。始终检查输入函数中的错误条件,函数是否为 getchar() , scanf() , fread() , read()或他们无数的亲戚中的任何一个。

关于c - 一个句子的平均字长,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17128722/

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