简体   繁体   中英

C - Find maximum value in array

I'm working on a program here and I am accessing file input and am looping through an array of values in the file. However, it's not properly calculating the maximum value. Any help?

#include <stdio.h>

int main() {

int header, i, j, cur_val, auction[50], sum = 0;
int max = 0;

FILE * ifp;

ifp = fopen("input.txt", "r");

fscanf(ifp, "%d", &header);

for (i = 0; i < header; i++) {

    fscanf(ifp, "%d", &cur_val);
    printf("%d\n", cur_val);

    for (j = 0; j < cur_val; j++) {
        fscanf(ifp, "%d", &auction[j]);

        printf("%d\n", auction[j]);

        max = auction[0];
        if (auction[j] > max) {
            max = auction[j];
        }

    }//end j loop

    printf("Max: %d\n", max);
    printf("\n");
    //printf("Auction %d was sold for $%.2f!\n", i+1, );
    //sum+=max;

}//end i loop

fclose(ifp);


return 0;

}

Here's the file input:

5

4

100 500 250 300

1

700

3

300 150 175

2

920 680

8

20 10 15 25 50 30 19 23

The max values printed to the console are as follows:

300 700 300 920 23

The middle 3 work but not the first and last. Any idea why?

You set max = auction[0]; on every loop, eliminating your previous max value.

Initialize the max value only once within the loop, or initialize max outside the loop (after reading the first value).

您在列表中找到比拍卖更大的最后一个数字[0]

The canonical implementation of a linear max_value loop is something like this

Given

  • N values
  • MIN_N <= N <= MAX_N

max_value = MIN_N for i in 1...N if values[i] > max_value max_value = values[i]

Now, you can either read all the values into an array (I've called it values above), or simply read in the values one at a time.

Converting this to C, and assuming an array for simplicity here:

int max_value = MIN_N;
for (int i = 0; i < N; ++i) {
    if (values[i] > max_value)
        max_value = values[i];
}
printf("Max %d\n", max_value);

For your actual assignment, you need to wrap this in a loop to deal with all the test cases. I'd probably read numbers as I went to avoid the need for memory management etc.

FILE *f = open_input_file(); // could return stdin for testing
int T = read_an_integer(f);

for (int t = 0; t < T; +=t) {
    int N = read_an_integer(f);
    int max_value = MIN_N;

    if (N <= 0) continue;

    for (int n = 0; n < N; ++n) {
        int v = read_an_integer(f);
        if (v > max_value)
             max_value = v;
    }

    printf("Max %d\n", max_value);
}
close_my_file(f);

I'll leave the file handling and I/O as an exercise - but make sure you deal with all error conditions (in this case calling exit(-1) is probably sufficient).

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