gpt4 book ai didi

计算单词的平均长度(不够精确)

转载 作者:行者123 更新时间:2023-12-02 09:16:41 27 4
gpt4 key购买 nike

我编写了一个程序,最多需要 100 个单词并将它们存储在一个数组中。然后它计算出单词的平均长度并将结果打印到 stderr。我的程序在我的所有测试脚本上都运行良好,除了一个,在给定的测试脚本中,平均值计算为 4.04,但我需要它为 4.02。我不确定为什么我的答案不够准确?干杯

程序 -

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void *emalloc(size_t s) {
void *result = malloc(s);
if (NULL == result) {
fprintf(stderr, "Memory allocation failed!\n");
exit(EXIT_FAILURE);
}
return result;
}

/* n is the size of the array */
void print_array(char **a, int n, double average) {
if (n == 0) {
/* do nothing */
} else {
if (strlen(a[0]) > average) {
fprintf(stdout, "%s\n", a[0]);
}
print_array(a + 1, n - 1, average);
}
}

int main()
{
#define SIZE 100
char *username[100];
char word[80];
int num_words = 0;
int p;
float average = 0.0;

/* Read words into array */


while(1 == scanf("%s", word)) {
username[num_words] = emalloc((strlen(word) + 1) * sizeof(word[0]));
strcpy(username[num_words], word);
num_words++;
}

/* Print out array */
for (p = 0; p < num_words; p++) {
average += strlen(username[p]);
}

average = average / num_words;

print_array(username, num_words, average);

if (average > 0) {
fprintf(stderr, "%.2f\n", average);
}

return EXIT_SUCCESS;
}

单词测试文件 -

hello
hi there
The quick brown fox jumps over the lazy dog
Mary had a little lamb
Little lamb little lamb
Mary had a little lamb
Its fleece was white as snow

Everywhere that Mary went
Mary went, Mary went
Everywhere that Mary went
The lamb was sure to go

It followed her to school one day
School one day, school one day
It followed her to school one day
Which was against the rules

It made the children laugh and play
Laugh and play, laugh and play
It made the children laugh and play
To see a lamb in school

最佳答案

您在总字长中包含了标点符号(例如,以“Mary gone”开头的行中的 ,)。

这足以破坏你的结果。

您可以使用 C 标准库函数 isalpha 消除此类字符。

另请注意,这里可能会出现未定义的行为:读入单词时可能会溢出内存缓冲区。这可能在这里也会产生影响。为什么不计算运行平均值:根本不需要存储单词?

关于计算单词的平均长度(不够精确),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46599869/

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