计算数组的一部分的平均值

时间:2017-02-12 18:49:51

标签: c arrays mean

我正在尝试计算用户输入的高温和低温的平均值,并且可以包含的天数在1到4之间,但是,我很难理解如何解决这个问题。我写的代码产生了一个完全不相关的数字。这是我的代码:

#include <stdio.h>

int main (void)
{
    int i;
    int limit;
    int day[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
    int high[10],low[10];

    printf("---===IPC Temperature Analyzer V2.0===---\n");

    printf("Please enter the number of days between 3 and 10, inclusive: ");
    scanf("%d", &limit);
    while (limit <= 2 || limit >= 11) {
        printf("Invalid entry, please enter a number between 3 and 10,   inclusive: ");
        scanf("%d", &limit);
    }

    for(i = 0;i < limit; i++) {
        printf("Day %d - High: ", day[i]);
        scanf("%d", &high[i]);
        printf("Day %d - Low: ", day[i]);
        scanf("%d", &low[i]);
    }

    printf("\nDay Hi Low\n");
    for (i = 0; i < limit; i++) {
        printf("%d   %d    %d\n", day[i], high[i], low[i]);
    }

    int max = 0;
    int min = 0;

    for (i = 0; i < limit; i++) {
        if (high[max] < high[i])
            max = i;
        if (low[min] < low[i])
            min = i;
    }

    printf("\nHighest temperature was: %d on day %d", high[max], day[max]);
    printf("\nLowest temperature was: %d on day %d ", low[min], day[min]);

    int n;
    int avg = high[i] + low[i]/i;

    printf("\nEnter a number between 1 and 4 to see the average temperature for the entered number of days, enter a negative number to exit\n");
    scanf("%d", &n);

    while (n > 4) {
        printf("Invalid entry, please enter a number between 1 and 4, inclusive: ");
        scanf("%d", &n);
    }

    while (n < 0) {
        printf("Goodbye!\n");
        exit(0);
    }

    for (i = 0; i < n; i++) {
        printf ("The average temperature up to day %d is: %d", day[i], avg);
    }
    return 0;
}

1 个答案:

答案 0 :(得分:2)

我想你错位了表达式int avg = high[i] + low[i]/i,而且这个含义对我来说似乎不正确:

首先:我想您想要在循环i : 0..n-1中打印每个特定日期的平均值,但是您只在循环外计算一次该值(并且您可能会想到i地方意味着。

第二:你每天只有两个值,即高和低,而不是i值,对吧?因此,要获得特定日期的平均温度,应该是avg = (high[i] + low[i])/2。还要注意大括号,它产生的运算符优先级与代码不同。如果你想计算一个&#34;总计&#34;平均到某一天,我将公式明确化,例如通过将averageOfDay与averageAverage区分开来。

第三:你确定avg应该是一个int吗?我建议使用浮动。

float avgSum = 0.0;
for (i = 0; i < n; i++) {
    float avgOfDay = (high[i] + low[i])/2.0;
    avgSum += avgOfDay;
}
float overallAvg = avgSum/n;
printf ("The average temperature up to day %d is: %f", day[n-1], overallAvg);