简体   繁体   中英

how to find the min/max of values within a file

#include <stdio.h>
int main(void)
{
    int num, i, total, average, min, max;
    min = num;
    max = num;
    FILE *ifile;
    ifile = fopen("scores.txt", "r");

    i = total = 0;
    while (fscanf(ifile, "%d", &num) != EOF) {
        i++;
        total += num;
    }

    printf("The total of the integers is %d.\n", total);
    printf("The number of integers in the file is %d.\n", i);

    average = total/i;

    printf("The average of the integers is %d.\n", average);

    while (fscanf(ifile, "%d", &num) != EOF) {
        if (num < min) {
            printf ("The minimum is %d\n", min);
        } else if (num > max) {
            printf ("The maximum is %d\n", max);
        }
    }

    fclose(ifile);
    return (0);
}

The part of the code that's wrong is the very end about mins/maxes. I'm not sure whether to put in a loop for this or to even make min and max variables themselves.

There are at least three issues in your min/max-detection loop:

First, as indicated by chux, min and max are not initialized; hence, when iterating through the numbers, statement if (num < min)... is far from guaranteed to work properly (same for max , of course). So initialize min with INT_MAX , and initialize max with INT_MIN (both defined in <limits.h> ), such that already in the first iteration min and max will be set to values from your file.

Second, the check for if (num < min)... gives you a "local" minimum, ie the minimum for all the numbers read so far, but not the "absolute" minimum, as there may come smaller numbers at a later point. So min/max will be valid at the end of the loop, not during the iteration.

Third, if (num < min) ... else if (num > max) is wrong at least if the file contains just one number.

Your code could look like the following:

int min = INT_MAX;
int max = INT_MIN;
while (fscanf(ifile, "%d", &num) != EOF) {
    if (num < min)
        min = num;
    if (num > max)
        max = num;
}
// min/max are valid earliest at this point:
printf ("The minimum is %d\n", min);
printf ("The maximum is %d\n", max);

// Note that min/max will not be correct if the file does not contain any number;
// Note further, that fscanf(ifile, "%d", &num) != EOF may result in an endless loop if the file contains characters that "%d" will not read as a valid integral value.
// But this is left to the OP for further improvement :-)

Consider the following modification to your code:

#include <stdio.h>

int main(void) {
    int num, i, total, average, min, max;

    // open file
    FILE *ifile = fopen( "scores.txt", "r" );
    // if opening file fails, print error message and exit 1
    if (ifile == NULL) {
        perror("Error: Failed to open file.");
        return 1;
    }

    // initialize i and total to zero.
    i = total = 0;
    // read values from file until EOF is returned by fscanf,
    //   or until an error (hence the comparison "== 1")
    while(fscanf(ifile, "%d", &num) == 1) {
        // In first round of loop, initialize min and max
        //   to the number being read (num)
        // After min/max have been initialized, they can then
        //   be compared and modified in the second if statement 
        //   in the remaining loop rounds
        if (i == 0) {
            min = num;
            max = num;
            total += num;
            ++i;
            continue;
        } 
        if (num < min) {
            min = num;
        } else if (num > max) {
            max = num;
        }
        total += num;
        ++i;
    }

    // initialize average
    average = total/i;

    // summary
    printf("The sum of all integers in file is %d.\n", total);
    printf("The number of integers in file is %d.\n", i);
    printf("The average of all integers in file is %d.\n", average);
    printf ("The minimum is %d\n", min);
    printf ("The maximum is %d\n", max);

    fclose(ifile);
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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