在for循环中嵌套if循环

时间:2016-03-18 02:23:37

标签: c loops if-statement for-loop nested

此代码只生成一个随机数作为温度,并每小时记录一次。获取代码的最大值和最小值时,我的for循环出现问题。它对我来说是正确的,类似于我看到的所有例子,但它给了我错误的输出。

谢谢

#include <stdio.h>
#include <stdlib.h>

void GetValue(int[], int x);
#define array_size 25
int main()  {
    int x, max, min, temperature[25];
    float sum;
    float average;
    int array[array_size];

printf("Temperature Conditions on October 9, 2015:\n");
       printf("Time of Day \t Temperature in Degrees F\n");

for (x = 0; x < 25; x++)    {
    //if statements to get min and max
    GetValue(temperature, x);
    if (temperature[x] > max)   {
        max = temperature[x];
    }
    if (temperature[x] < min)   {
        min = temperature[x];
    }
    printf("%d \t \t \t %d\n", x,temperature[x]);
}

//prints statements

printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", temperature[12],max, min);

//adds up all temps

sum=0;

for (x=0;x<25;x++){

    sum=(sum+temperature[x]);
}

//prints and creates average

average=sum/25;

printf("Average Temperature for the day: %.2f Degrees F\n",average);

return 0;

}
//gets values and puts them into array

void GetValue(int value[], int x) {

value[x] = (rand()%(100-60+1))+60;
}

1 个答案:

答案 0 :(得分:1)

您使用具有自动存储持续时间的未初始化变量的值来调用 undefine behavior ,这是不确定的。

  • 仅在为其指定一些值后才使用变量值。
  • 正确格式化代码。
  • 匹配printf()的格式说明符和数据。
  • 避免使用幻数。在这种情况下,请使用#define d数字表示元素数量。

更正后的代码:

#include <stdio.h>
#include <stdlib.h>

void GetValue(int[], int x);
#define array_size 25
int main(void) {
    int x, max = 0, min = 0, temperature[array_size];
    float sum;
    float average;

    printf("Temperature Conditions on October 9, 2015:\n");
    printf("Time of Day \t Temperature in Degrees F\n");

    for (x = 0; x < array_size; x++)    {
        //if statements to get min and max
        GetValue(temperature, x);
        // in the first iteration, there won't be a valid number in max and min
        if (x == 0 || temperature[x] > max)   {
            max = temperature[x];
        }
        if (x == 0 || temperature[x] < min)   {
            min = temperature[x];
        }
        printf("%d \t \t \t %d\n", x, temperature[x]);
    }

    //prints statements

    printf("\nMaximum Temperature for the day: %d Degrees F\nMinimum Temperature for the day: %d Degrees F\n", max, min);

    //adds up all temps

    sum=0;

    for (x=0;x<array_size;x++){

        sum=(sum+temperature[x]);
    }

    //prints and creates average

    average=sum/array_size;

    printf("Average Temperature for the day: %.2f Degrees F\n", average);

    return 0;

}
//gets values and puts them into array

void GetValue(int value[], int x) {

    value[x] = (rand()%(100-60+1))+60;
}
相关问题