Home > OS >  Find the maximum, minimum, and average values in the array
Find the maximum, minimum, and average values in the array

Time:05-13

In my code, the program will not allowed the negative number entered, the program will stop reading, then calculate the maximum value, minimum value and average value. That is my code

#include <stdio.h>

int main(void) {
  int age[10] = {0};              // initalized an array
  printf("Please enter ages: \n");  // allow user to enter numbers


  for (int i = 0 ;i < 10; i  ) {
    scanf("%d",&age[i]);
    if (age[i] < 0) { // if it is negative number, it is should stop reading
      break;
    }
    else if (age[i] >= 0) {
      continue;
    }
  }
  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;
  int length = sizeof(age) / sizeof(age[0]);
  for (int j = 0; j < length; j  ) {
    if (maximum < age[j]) {
      maximum = age[j];
    } 
    else if (minimum > age[j]) {
      minimum = age[j];
    }
    average  = age[j];
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}

Please enter ages: 5 -1 expected result: max:5;min:5,average:5;

actual result: max:5;min:-1,average: 0.4;

That was a question that I met, the code should not accept any negative value.

Thank you all. but if I add age[i] = 0; then break; The average value will equal to 0.5.

CodePudding user response:

  • You don't need an array.
  • You don't need both a loop variable and a length.
  • It's more appropriate to use ? : for updating minimum/maximum.
  • You don't need two loops
  • You need to check the int return value of scanf(), which indicates the number of items successfully scanned, so it should be 1. I'll leave that for you/OP to add (hint: replace for-loop by while-loop to avoid having to add a separate length variable again).
    int main(void)
    {
        printf("Please enter ages: \n");

        int minimum = INT_MAX;
        int maximum = 0;
        int sum = 0;
        int count = 0;

        for (count = 0; count < 10; count  )
        {
            int age;
            scanf("%d", &age);

            if (age < 0)
            { 
                break;
            }

            sum  = age;

            minimum = (age < minimum) ? age : minimum;
            maximum = (age > maximum) ? age : maximum;
        }

        if (count > 0)
        {
            printf("Min: %d\n", minimum);
            printf("Max: %d\n", maximum);
            printf("Avg: %.1f\n", (float)sum / count);
        }
        else
        {
            printf("You didn't enter (valid) age(s).\n");
        }

        return 0;
    }

CodePudding user response:

Your approach is overly complicated and wrong.

You want this:

  ...
  int length = 0;    // declare length here and initialize to 0

  for (int i = 0; i < sizeof(age) / sizeof(age[0]); i  ) {
    scanf("%d", &age[i]);

    if (age[i] < 0)  // if it is negative number, it is should stop reading
      break;

    length  ;        // one more valid number
  }
  
  // now length contains the number of numbers entered
  // the rest of your code seems correct

You also might need to handle the special case where no numbers are entered, e.g: the only thing entered is -1. It doesn'make sense to calculate the average or the largest/smallest number when there are no numbers.

CodePudding user response:

A possible solution could be:

(corrections are written in the commented code)

#include <stdio.h>

int main(void){
  int arraySize = 10;
  int age[arraySize]; //initialize not required
  
  //the number of existing values inside the array (effective length)
  int length = 0;

  printf("Please enter ages: \n");  // allow user to enter numbers

  for(int i=0; i<arraySize; i  ){
    scanf("%d",&age[i]);
    
    // if it is negative number, it is should stop reading
    if(age[i]<0){ break; }
    
    //the else-if is not required
    //but, if the compiler goes here,
    //it means that the value is acceptable, so
    length  ;
  }

  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;
   
  for(int j=0; j<length; j  ){
    if(maximum<age[j]){ maximum = age[j]; } 
    else if(minimum>age[j]) { minimum = age[j]; }
    average  = age[j];
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}

CodePudding user response:

OP's primary problem is the 2nd loop iterates 10 times and not i times (the number of times a non-negative was entered.


For fun, let us try a non-floating point solution as it really is an integer problem.

An array to store values is not needed.

#include <limits.h>
#include <stdio.h>

int main(void) {
  // Keep track of 4 things
  int min = INT_MAX; // Set min to the max int value.
  int max = INT_MIN;
  long long sum = 0; // Use wide type to cope with sum of extreme ages.
  int count = 0;

  #define INPUT_N 10

  printf("Please enter ages: \n");
  
  for (count = 0; count < INPUT_N; count  ) {
    int age;
    if (scanf("%d", &age) != 1) {
      fprintf(stderr, "Missing numeric input.");
      return EXIT_FAILURE;
    }
    if (age < 0) {
      break;
    }

    if (age < min) min = age;
    if (age > max) max = age;
    sum  = age;
  }

  if (count == 0) {
    fprintf(stderr, "No input.");
    return EXIT_FAILURE;
  }

  printf("Maximum: %d\n", max);
  printf("Minimum: %d\n", min);

  // Could use FP and 
  // printf("Average: %.1f\n", 1.0 *sum / count);
  // But for fun, how about a non-FP approach?
 
  #define SCALE 10
  #define SCALE_LOG 1
  sum *= SCALE; // Scale by 10 since we want 1 decimal place.
  // Perform a rounded divide by `count`
  long long average_scaled = (sum   count/2) / count;
  // Print the whole and fraction parts
  printf("Average: %lld.%0.*lld\n", 
      average_scaled / SCALE, SCALE_LOG, average_scaled % SCALE);

  return 0;
}

CodePudding user response:

First of all, you must record how many positive numbers you enter. Then the value of length will be correct.

Second, for the second for loop, j must be smaller than the number of positive ages. Therefore, you won't add negative age[j] to average.

You can simply modify the second for loop.

#include <stdio.h>

int main(void) {
  int age[10] = {0};              // initalized an array
  printf("Please enter ages: \n");  // allow user to enter numbers


  int length = 0;

  for (int i = 0 ;i < 10; i  ) {
    scanf("%d",&age[i]);
    if (age[i] < 0) { // if it is negative number, it is should stop reading
      break;
    }
    else if (age[i] >= 0) {
      length  ;
      continue;
    }
  }
  int maximum = age[0];
  int minimum = age[0];
  float average = 0.0;

for (int j = 0; j < length; j  ) {
    if (maximum < age[j]) {
      maximum = age[j];
    } 
    else if (minimum > age[j]) {
      minimum = age[j];
    }

    if ( age[j] > 0.0 )
    {
      average  = age[j];
    }
  }

  average = average / length;
  printf("%d\n", maximum);
  printf("%d\n", minimum);
  printf("%.1f\n", average);

  return 0;
}
  •  Tags:  
  • c
  • Related