简体   繁体   中英

Problem to find ID number from min & max values

So I am trying to make a simple program that reads integers of values and ID number so the output will be minimum maximum of the value and its maxID minID number. The first integer of the input file will indicate how many more input will be read in loops. My program compiles without any problem and minimum maximum output are correct however,the output of ID numbers are wrong. Could anyone help me with diagnose this issue? Sorry for my silly question, I am new in programming. Thanks.

#include <stdio.h>

int main(){

int val[100],id[100];
int i, max, min, size, idmax, idmin,minindex,maxindex;

printf("Enter how many IDs: ");
scanf("%d", &size);

printf("Enter ID numbers and values:\n");
for(i=0; i<size; i++)
{
    scanf("%d %d", &id[i], &val[i]);
}


max = min = val[0];

for(i=1; i<size; i++)
{
    if(val[i] > max)
    {
        max = val[i];
        maxindex = i;
        for(i=0;i<size;i++){
          if(id[i]==maxindex){
            idmax=id[i];
          }
        }
      }

    if(val[i] < min)
    {
        min = val[i];
        minindex = i;
        for(i=0;i<size;i++){
          if(id[i]==minindex){
            idmin=id[i];
          }
        }
    }
}

printf("Max number = %d with ID number = %d\n", max, idmax);
printf("Min number = %d with ID number = %d\n", min, idmin);

return 0;

}

You are making the problem more complicated than it actually is. When running through the;list, you can simply update the idmax or idmin value whenever you update the corresponding max or min :

#include <stdio.h>

int main() {

    int val[100], id[100];
    int i, max, min, size, idmax, idmin;/// No longer need these: minindex, maxindex;

    printf("Enter how many IDs: ");
    scanf("%d", &size);

    printf("Enter ID numbers and values:\n");
    for (i = 0; i < size; i++) {
        scanf("%d %d", &id[i], &val[i]);
    }

    max = min = val[0];
    idmin = idmax = id[0];/// Initialize IDs similarly to min and max

    for (i = 1; i < size; i++) {
        if (val[i] > max) {
            max = val[i];
            idmax = id[i];/// Only need to change this when max changes
        }
        if (val[i] < min) {
            min = val[i];
            idmin = id[i];/// Only need to change this when min changes
        }
    }

    printf("Max number = %d with ID number = %d\n", max, idmax);
    printf("Min number = %d with ID number = %d\n", min, idmin);

    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