为什么我的第一个值不能正确打印,但是后面的每个值都可以正确打印

时间:2019-04-07 16:53:14

标签: c multidimensional-array

我的目标是在6个不同的湖泊中获得最低的温度值,我能够获得除第一个值(优越的湖泊)之外的所有值,我该如何打印该值?

我尝试将最冷温度的初始值设置为数组的第一行,以便可以将其与大于0的值进行比较(文件中的任何值都不小于0)

这是我用于此问题的文件数据,其格式为年/日/然后依次是每个湖泊 https://drive.google.com/file/d/1ADaYffIlMjsZbGMA-85adDg2uXLydshY/view?usp=sharing

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

int main(void)
{
/* variables */
    double alltemps[365][8], coldest[6], coldestday[6], coldestmonth[6];
    int i, j;

/* j = rows, i = columns */

/* open file and assign values to the array */
    FILE*WaterTemperatureData;

    WaterTemperatureData=fopen("WaterTemperatureData.txt", "r");

    for(j=0;j<365;++j)
    {
        for(i=0;i<8;++i)
        {
            fscanf(WaterTemperatureData, "%lf", &alltemps[j][i]);
        }

    }

/* determine coldest temps for each lake */
for(i=2; i<8; ++i)
    {    
        for(j=0; j<365; ++j)
        {
            coldest[i-1] = alltemps[0][i];

            if (alltemps[j][i] < coldest[i-2])
            {
                coldest[i-2] = alltemps[j][i];
                coldestday[i-2] = alltemps[j][1];
            }
        }
    }

/* output statements */
    printf("Coldest Temperature of Lake Superior is %2.2lf on %0.0lf\n", coldest[0],coldestday[0]);
    printf("Coldest Temperature of Lake Michigan is %2.2lf on %0.0lf\n", coldest [1],coldestday[1]);
    printf("Coldest Temperature of Lake Huron is %2.2lf on %0.0lf\n", coldest [2],coldestday[2]);
    printf("Coldest Temperature of Lake Erie is %2.2lf on %0.0lf\n", coldest [3],coldestday[3]);
    printf("Coldest Temperature of Lake Ontario is %2.2lf on %0.0lf\n", coldest [4],coldestday[4]);
    printf("Coldest Temperature of Lake St. Clair is %2.2lf on %0.0lf\n", coldest [5],coldestday[5]);    

return(0);
}

对于苏必利尔湖,我希望在第72天获得1.33,而不是在第0天获得0

1 个答案:

答案 0 :(得分:0)

  

为什么我的第一个值不能正确打印(?)

coldest[i-2]在分配前使用-> 未定义行为(UB)。

for(i=2; i<8; ++i)
  // coldest[2-2] never  assigned
  if (alltemps[j][i] < coldest[i-2])