简体   繁体   English

在 FILE,c 语言中查找最低和最高温度

[英]Finding min and max temperature in FILE, c language

I am trying to make this code to work but my ability in programming is not good enough, so i thought i should ask you after so many search i did.我试图让这段代码工作,但我的编程能力不够好,所以我想我应该在我做了这么多搜索之后问你。

So, I've made a program which makes a binary .dat file which includes 2 integers (day and month) and 2 floats (min,max temperatures of the day).所以,我制作了一个程序,它生成一个二进制 .dat 文件,其中包括 2 个整数(日和月)和 2 个浮点数(当天的最低、最高温度)。 My homework says that it needs from ALL the inputs i did, the minimum temperature and the maximum temperature and print them with the day included.我的作业说它需要我所做的所有输入,最低温度和最高温度,并将它们打印出来,包括当天。 I am stuck at "searching" from all the inputs, the minimum and the maximum seperately.我被困在从所有输入中“搜索”,分别是最小值和最大值。

I hope you understand, my english is not good enough.我希望你明白,我的英语不够好。

I can't remember what i've tried so far.我不记得到目前为止我尝试过什么。 But i am stuck here.但我被困在这里。

EDIT: I've edited the code to make things more clearly.编辑:我已经编辑了代码以使事情更清楚。

#include <stdio.h>

typedef struct {
    int day, month;
    float max_temp, min_temp;
} Date;

Date D;

int main() {
    FILE *f, *t;
    float min = D.min_temp, max = D.max_temp;
    f = fopen("Metriseis_2012.dat", "rb");

    while (!feof(f)) {
        fread(&D, sizeof(Date), 1, f);
        if ((!feof(f)) && (D.min_temp < min)) {
            fseek(f, sizeof(Date), SEEK_SET);
            printf("\nDay %d\nMonth %d\nMin_Temp %.2f\nMax_Temp %.2f\n\n", D.day, D.month, D.min_temp, D.max_temp);
        }
    }
    fclose(f);
    return 0;
}

Generate data to be used to test the main algorithm生成用于测试主要算法的数据

Here's some code to write a binary file containing date and temperature values (a necessary precursor to writing code to read such data):下面是编写包含日期和温度值的二进制文件的一些代码(编写代码以读取此类数据的必要前提):

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

typedef struct
{
    int   day;
    int   month;
    float max_temp;
    float min_temp;
} Date;

int main(void)
{
    const char filename[] = "Metriseis_2012.dat";
    FILE *fp = fopen(filename, "wb");
    if (fp == NULL)
    {
        fprintf(stderr, "Failed to open file '%s' for writing\n", filename);
        exit(EXIT_FAILURE);
    }

    for (int i = 0; i < 30; i++)
    {
        Date D =
        {
            .day = rand() % 28 + 1, .month = rand() % 12 + 1,
            .min_temp = rand() % 20,
        };

        D.max_temp = rand() % 50 + D.min_temp;
        printf("Day temperature: %6.2f - %6.2f on %.2d-%.2d\n", D.min_temp, D.max_temp, D.month, D.day);
        if (fwrite(&D, sizeof(D), 1, fp) != 1)
        {
            fprintf(stderr, "failed to write to '%s'\n", filename);
            exit(EXIT_FAILURE);
        }
    }

    fclose(fp);
    return 0;
}

The data generation code does not preclude repeats in the date (and indeed, the dates 02-08 and 08-01 both repeat in the sample data, with different temperature ranges).数据生成代码不排除日期重复(事实上,日期02-0808-01在样本数据中都重复,具有不同的温度范围)。 Fixing that is moderately hard.修复它是中等难度的。 The generated data is not sorted into date order.生成的数据未按日期顺序排序。

The separate assignment to D.max_temp avoids running foul of the indeterminate evaluation order specified in C11 §6.7.9 Initialization ¶23 :D.max_temp的单独分配可避免违反 C11 §6.7.9 初始化 ¶23 中指定的不确定评估顺序:

The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified.初始化列表表达式的计算相对于彼此是不确定的,因此任何副作用发生的顺序是不确定的。 152) 152)

152) In particular, the evaluation order need not be the same as the order of subobject initialization. 152) 特别是,评估顺序不必与子对象初始化的顺序相同。

You could add:你可以添加:

#include <time.h>

and (at the top of main() ):和(在main()的顶部):

    srand(time(0));

so that it generates different sequences of numbers when it is called no more frequently than once a second.这样当它被调用的频率不超过每秒一次时,它会生成不同的数字序列。 There are other, better ways to seed the random number generator, but they involve more code (and often some platform specific code too).还有其他更好的方法来为随机数生成器提供种子,但它们涉及更多代码(通常还有一些特定于平台的代码)。

Determine minimum and maximum temperatures and corresponding dates确定最低和最高温度以及相应的日期

Here's code that reads the data and determines the date on which the minimum temperature was recorded (and the minimum value), and the date on which the maximum temperature was recorded (and the maximum value).这是读取数据并确定记录最低温度(和最小值)的日期以及记录最高温度(和最大值)的日期的代码。

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

typedef struct
{
    int day, month;
    float max_temp, min_temp;
} Date;

int main(void)
{
    const char filename[] = "Metriseis_2012.dat";
    FILE *fp = fopen(filename, "rb");

    if (fp == NULL)
    {
        fprintf(stderr, "Failed to open file '%s' for reading\n", filename);
        exit(EXIT_FAILURE);
    }

    Date Dmin = { 0, 0, 100.0, 100.0 };
    Date Dmax = { 0, 0,   0.0,   0.0 };
    Date D;
    while (fread(&D, sizeof(Date), 1, fp) == 1)
    {
        printf("Day temperature: %6.2f - %6.2f on %.2d-%.2d\n", D.min_temp, D.max_temp, D.month, D.day);
        if (D.max_temp > Dmax.max_temp)
            Dmax = D;
        if (D.min_temp < Dmin.min_temp)
            Dmin = D;
    }
    fclose(fp);

    printf("Min temperature: %6.2f on %.2d-%.2d\n", Dmin.min_temp, Dmin.month, Dmin.day);
    printf("Max temperature: %6.2f on %.2d-%.2d\n", Dmax.max_temp, Dmax.month, Dmax.day);

    return 0;
}

On my Mac, the output I got from the reading code was:在我的 Mac 上,我从阅读代码中得到的输出是:

Day temperature:  13.00 -  21.00 on 02-08
Day temperature:   4.00 -  32.00 on 09-07
Day temperature:   0.00 -  15.00 on 02-16
Day temperature:   7.00 -  10.00 on 03-01
Day temperature:   0.00 -  12.00 on 02-24
Day temperature:   9.00 -  16.00 on 02-12
Day temperature:  19.00 -  47.00 on 10-09
Day temperature:  17.00 -  43.00 on 08-01
Day temperature:  10.00 -  43.00 on 08-01
Day temperature:  19.00 -  40.00 on 02-08
Day temperature:  13.00 -  49.00 on 09-28
Day temperature:   8.00 -  49.00 on 06-10
Day temperature:   1.00 -   4.00 on 02-07
Day temperature:   8.00 -  48.00 on 05-01
Day temperature:  10.00 -  13.00 on 09-17
Day temperature:   9.00 -  33.00 on 11-27
Day temperature:  17.00 -  25.00 on 02-02
Day temperature:  18.00 -  49.00 on 02-17
Day temperature:   5.00 -  19.00 on 02-20
Day temperature:   5.00 -  24.00 on 01-08
Day temperature:   9.00 -  10.00 on 11-28
Day temperature:   5.00 -   9.00 on 12-02
Day temperature:   8.00 -  31.00 on 07-04
Day temperature:  12.00 -  28.00 on 11-26
Day temperature:  18.00 -  62.00 on 10-21
Day temperature:  11.00 -  39.00 on 10-06
Day temperature:  17.00 -  64.00 on 03-14
Day temperature:   9.00 -  40.00 on 01-27
Day temperature:  15.00 -  63.00 on 04-18
Day temperature:   8.00 -  20.00 on 08-03
Min temperature:   0.00 on 02-16
Max temperature:  64.00 on 03-14

There are two entries for the minimum temperature — the first is selected.最低温度有两个条目——第一个被选中。 A more complex test could choose the earliest date or latest date.更复杂的测试可以选择最早日期或最晚日期。

It would be sensible to have the generator program accept command line arguments that specify the output file name and a number of output records to generate.让生成器程序接受指定输出文件名和要生成的输出记录数量的命令行参数是明智的。 The analyzer program should accept command line arguments that specify the file name(s) to be processed.分析器程序应该接受指定要处理的文件名的命令行参数。

Hopefully the following code can help you.希望以下代码可以帮助您。 If you know the number of lines beforehand, it will be easier.如果你事先知道行数,那会更容易。 In this example I used 4 lines in the .dat file.在这个例子中,我在 .dat 文件中使用了 4 行。

#include <stdio.h>
#include <malloc.h>
#include <float.h>

typedef struct {
    int day, month;
    float max_temp, min_temp;
} Date;

Date D;

int main(void) {
    int LINE_NUMBERS = 4;
    FILE *fp;
    float min = FLT_MAX;
    float max = FLT_MIN ;
    fp = fopen("Metriseis_2012.dat", "r");
    Date *t_date = malloc(sizeof(Date)*LINE_NUMBERS);
    int i = 0;
    if (fp != NULL) {
        while (i < LINE_NUMBERS) {
            fscanf(fp, "%d %d %f %f",
                   &t_date[i].day,
                   &t_date[i].month,
                   &t_date[i].max_temp,
                   &t_date[i].min_temp);
            i++;
        }
    } else {
        perror("FP ERROR: ");
    }
    for (i = 0; i < LINE_NUMBERS; i++) {
        printf("%d %d  %f %f\n",
               t_date[i].day,
               t_date[i].month,
               t_date[i].max_temp,
               t_date[i].min_temp);
        if (min > t_date[i].min_temp)
            min = t_date[i].min_temp;
        if (max < t_date[i].max_temp)
            max = t_date[i].max_temp;
    }
    fclose(fp);
    printf("max %f min %f\n", max, min);
    return 0;
}

Example .dat file示例 .dat 文件

1 2 3 4 
5 6 7 8
12 23 34 45
12 3 34 45

Output输出

1 2  3.000000 4.000000
5 6  7.000000 8.000000
12 23  34.000000 45.000000
12 3  34.000000 45.000000
max 34.000000 min 4.000000

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

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