无法将for循环增量分配给int变量

问题描述 投票:0回答:1

我正在编写一个程序,该程序从2个列表中获取最高/最低值并将其记录下来,以及它们出现在哪个循环增量处。

这是导致问题的我的代码部分。您在此处看到的所有变量都已提前声明:

for(int i = 0; i < days; i++){
    highest_temp = high_temp[i];
    lowest_temp = low_temp[i];

    while (high_temp[i] > highest_temp){
        highest_temp = high_temp[i];
        highest_temp_day = i+1;
    }

    while  (low_temp[i] < lowest_temp){
        lowest_temp = low_temp[i];
        lowest_temp_day = i+1;
    }
}

printf("\n\nThe highest temperature was %d, on day %d", highest_temp, highest_temp_day);
printf("\nThe lowest temperature was %d on day %d", lowest_temp, lowest_temp_day);

这是我的输出:

The highest temperature was 9, on day 0
The lowest temperature was -4 on day 0

highest_temp_daylowest_temp_day变量都被初始化为0,但在while循环中没有更新。

c int
1个回答
2
投票

您的代码需要重组:

// these need to be outside so they don't get redefined constantly
int highest_temp = high_temp[0];
int lowest_temp = low_temp[0];
// initialize these to the first day
int highest_temp_day = 0;
int lowest_temp_day = 0;
// iterate through the array
for (int i = 0; i < days; i++) {
    // change whiles to ifs
    if (high_temp[i] > highest_temp) {
        // update vars
        highest_temp = high_temp[i];
        highest_temp_day = i + 1;
    }
    if (low_temp[i] < lowest_temp) {
        lowest_temp = low_temp[i];
        lowest_temp_day = i + 1;
    }
}

printf("\n\nThe highest temperature was %d, on day %d", highest_temp, highest_temp_day);
printf("\nThe lowest temperature was %d on day %d", lowest_temp, lowest_temp_day);
© www.soinside.com 2019 - 2024. All rights reserved.