【发布时间】:2017-10-18 00:34:15
【问题描述】:
我想从一个数组中生成算术平均值,但只能使用某个范围内的值(这里从 -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;
编辑:很抱歉,我一定是错过了暂时复制整个代码。
我知道这是一个简单的问题,但我似乎无法让它发挥作用。也许睡眠不足让我发疯了
【问题讨论】:
-
你运行它时发生了什么?
-
n的值是多少?你如何初始化sum?对于某些指定的输入,预期结果是什么,实际结果是什么?请花一些时间到read about how to ask good questions 学习如何创建Minimal, Complete, and Verifiable Example。 -
如果可以,那就没问题了。如果没有,请向我们展示整个代码并告诉我们您的错误。
-
"这段代码可以吗?" -- 没有。
n没有更新,没有检查范围内没有元素的数组,...跨度> -
@Badda 它可以工作,没关系 -- 不!