如何在此代码中获取Days的值?

时间:2017-06-04 17:03:27

标签: c

我试图显示4天的平均温度,最高和最低。该代码完美地显示了4天的平均值和最高/最低值。问题是试图显示它发生在哪一天。

我知道我不需要使用数组,我认为如果我使用它就很容易。所以,这是代码。如何改进它,以获得用户插入最高/最低值的日期?

int high[NUMS], low[NUMS];

int maximum = 40;
int minimum = -40;

int i, day;

float total, average;

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

for (i = 0; i < NUMS; ++i) {

    do{
        printf("Enter the high value for day %d: \n", i+1);
        scanf("%d", &high[i]);
        printf("Enter the low value for day %d: \n", i+1);
        scanf("%d", &low[i]);  


       if ((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i])){
                printf ("Incorrect values, temperatures must be in the range -40 to 40, high must be greater than low.\n");
        }

    } while((high[i] > maximum) || (low[i] < minimum) || (high[i] < low[i]));

    if((high[0] < high[i]))
       high[0] = high[i];

    if ((low[0] > low[i])) 
       low[0] = low[i];

    total = total + (high[i] + low[i]);

}

 average = (total / (NUMS * 2));

printf("The average (mean) temperature was: %.2f\n", average);
printf("The highest temperature was %d, on day %d\n", high[0], day);
printf("The lowest temperature was %d, on day %d\n", low[0], day);

return 0;

2 个答案:

答案 0 :(得分:2)

最简单的方法是在不改变代码的情况下声明两个变量day而不是一个:

int day_low = 0;
int day_high = 0;

然后更改以下if条件:

if((high[0] < high[i])) {
   high[0] = high[i];
   day_high = i;
}

if ((low[0] > low[i])) {
   low[0] = low[i];
   day_low = i;
}

最后:

printf("The highest temperature was %d, on day %d\n", high[0], day_high);
printf("The lowest temperature was %d, on day %d\n", low[0], day_low);

答案 1 :(得分:0)

感谢大家的帮助。我必须添加变量并按照提到的那样启动为0。

但仍然是错的。第一天显示为&#34;第0天和第34天。为了解决这个问题,我添加+1。

if((high[0] < high[i])){
       high[0] = high[i];
       highestDay = i + 1;
    }

    if ((low[0] > low[i])){ 
       low[0] = low[i];
       lowestDay = i + 1;
    }