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

Can't assign the for loop increment to an int variable

我正在编写一个程序,它从 2 个列表中获取 highest/lowest 值并记录它们,以及它们出现的 for 循环增量。

这是导致问题的代码部分。您在此处看到的所有变量均较早声明:

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 循环中更新。

您的代码需要重构:

// 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);