gpt4 book ai didi

c - 求元素平均值的问题

转载 作者:行者123 更新时间:2023-11-30 14:44:24 25 4
gpt4 key购买 nike

使用 Repl.it 并尝试使用 C 中的函数来平均可变长度数组中的元素。我的程序在除返回的平均值之外的所有其他 I/O 区域中都运行良好:

当天的平均值是:-nan。关于问题可能是什么的任何见解吗?

目标是以 double 形式接收用户输入(例如,7 小时内每小时抽取了多少品脱血液,然后使用函数调用来计算这 7 小时内的平均量。

新代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
double average(int size, float ary[*]);


int main(void)
{
char dayOne[8], dayTwo[8];
int size;
float ave;

printf("Over how many hours do you want to view donation amounts?: ");
scanf("%d", &size);
if (size < 7 || size > 7)
size = 7;
printf("Enter day that you want to see average donation amount for: ");
scanf("%s", dayOne);
{
float ary[size];

for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);

}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayOne, ave);
}

printf("\n\nEnter day that you want to see average donation amount for: ");
scanf("%s", dayTwo);

if(strcmp(dayOne, dayTwo)== 0)
printf("\nEnter a different day please: ");

scanf("%s", dayTwo);

{
float ary[size];

for (int i = 0; i < size; i++)
{
printf("\nEnter amount taken in hour %d:", i + 1);
scanf("%f", &ary[i]);
}
ave = average(size, ary);
printf("\nThe average donated for %s is: %2.1f", dayTwo, ave);

}


return 0;
}

double average(int size, float ary[])
{

double sum = 0;

double ave;

for (int i = 0; i < size; i++)
sum += ary[i];

ave = (double)sum / size;
return ave;
}

最佳答案

这是错误的:

int ary[7];

scanf("%f", &ary[i]);

%f 用于扫描 float,但 ary[i]int。结果行为未定义。

这是错误的:

double size;

ave = average(size, ary);

“...”中没有任何内容为 size 赋值,因此当调用 average 时,它没有定义的值。

关于c - 求元素平均值的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53510397/

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