Search code examples
csummaxaveragemin

Average subtracted of max and min returns wrong result


I want to find the average of 5 numbers apart from the max and min of the table.

Nevertheless the following code provides the wrong result.

#include <stdio.h> 

#define size 5

main() {
  int i;
  float table[size], max, min, mo, sum;
  max = 0;
  min = 0;
  mo = 0;

  printf("Provide a number: ");
  scanf("%f", &table[1]);
  max = table[1];
  min = table[1];

  for (i = 2; i <= size; i++) {
    printf("Provide a number: ");
    scanf("%f", &table[i]);

    if (max <= table[i])
      max = table[i];
    if (min >= table[i]) {
      min = table[i];
    }
    sum = sum + table[i];
  }

  mo = (sum - max - min) / (size - 2);
  printf("The average numberis: %f", mo);
}

Example:

If you input 1,2,3,4,5 the output will be 2,666667 instead of 3.

Could you please advise why this is happening?


Solution

  • I have edited the code based on the comments and it word properly. Thank you very much!

    #include <stdio.h> 
    
    #define size 5
    
    main() {
      int i;
      float table[size], max, min, mo, sum;
      max = 0;
      min = 0;
      mo = 0;
    
      printf("Provide a number: ");
      scanf("%f", &table[0]);
      max = table[0];
      min = table[0];
      sum = table[0];
    
      for (i = 1; i < size; i++) {
        printf("Provide a number: ");
        scanf("%f", &table[i]);
    
        if (max <= table[i])
          max = table[i];
        if (min >= table[i]) {
          min = table[i];
        }
        sum = sum + table[i];
      }
    
      mo = (sum - max - min) / (size - 2);
      printf("The average numberis: %f", mo);
    }