简体   繁体   English

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

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

I'm writing a program that takes the highest/lowest values from 2 lists and records them, as well as at which for loop increment they've appeared.我正在编写一个程序,它从 2 个列表中获取最高/最低值并记录​​它们,以及它们出现的 for 循环增量。

This is the part of my code that is causing the problem.这是我的代码中导致问题的部分。 All variables you see here were declared earlier:您在此处看到的所有变量都在之前声明过:

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

This is my output:这是我的输出:

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

The variables highest_temp_day and lowest_temp_day were both initialied to 0 but they're not updated inside the while loops.变量highest_temp_daylowest_temp_day都初始化为0,但它们不会在while 循环内更新。

Your code needs to be restructured:您的代码需要重构:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM