gpt4 book ai didi

c - c中范围-5到5的数组的算术平均值

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

我想从数组生成算术平均值,但仅限于特定范围内的值(此处为 -5 到 5)

这段代码可以吗?

#include <stdio.h>

int main()
{
int n, i;
float num[100], sum = 0.0, average;

printf("Enter the numbers of elements: ");
scanf("%d", &n);

while (n > 10 || n <= 0)
{
printf("Error! number should in range of (1 to 10).\n");
printf("Enter the number again: ");
scanf("%d", &n);
}

for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
if( num[i]< 5 && num[i]>-5){
sum+= num[i];

}

average = sum / n;
printf("Average = %.2f", average);

return 0;

编辑:很抱歉,我当时一时冲动,错过了复制整个代码。

这是一个我知道的简单问题,但我似乎无法让它发挥作用。也许 sleep 不足让我发疯

最佳答案

您的代码错误。

它的格式很糟糕,这就是为什么你不明白它为什么是错误的:

您的代码格式不正确:

...

for(i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i+1);
scanf("%f", &num[i]);
if( num[i]< 5 && num[i]>-5){
sum+= num[i];

} // it looks as if the for loop end here, but it doesn't

average = sum / n;
printf("Average = %.2f", average);

return 0;
} // the for loop actually ends here

相同的代码格式正确:

for (i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i + 1);
scanf("%f", &num[i]);

if (num[i]< 5 && num[i]>-5) {
sum += num[i];
}

average = sum / n;
printf("Average = %.2f", average);

return 0;
} // <<< the for loop ends here

正确的代码(查看注释以获取解释):

...
int nbofnumbers = 0; // number of numbers in the interval [-5,5]

for (i = 0; i < n; ++i)
{
printf("%d. Enter number: ", i + 1);
scanf("%f", &num[i]);

if (num[i]< 5 && num[i]>-5) {
nbofnumbers++;
sum += num[i];
}
} // for loop must end here

average = sum / nbofnumbers; // we divide by the number of numbers
// in the interval [-5,5], not by n
printf("Average = %.2f", average);

return 0;
...

关于c - c中范围-5到5的数组的算术平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44043617/

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