سؤال

I have to find the maximum and the minimum using a sentinel controlled repetition.

"maximum” is not working properly. Can anyone help me with some clue about what’s wrong in my code?

#include<stdio.h>

int main() { 
  int number;
  int min;
  int max;

  do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(number < min )
        min = number;
      if( number > max )
        max = number;

    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );

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

  system("pause");

  return 0;
}
هل كانت مفيدة؟

المحلول

The value of your variables not initialized were 2674276, all numbers were smaller so your min was fine

but no number was bigger than this so it was your max.

You need to initialize your min and your max with the first number

I would do something like

max = -1
min = -1

do {
    printf("Enter a number (-1 to quit): ");
    scanf("%d",&number);
    if( number >= 0 ) {
      if(max == -1)
      {
         max = number //Means it's the first time so your max and min are the first number
         min = number
      }
      else
      {
         if(number < min )
            min = number;
         if( number > max )
          max = number;

      }
    }
    else if( number < 1 )
      printf("the number is not valid \n");
  } 

  while( number != -1 );
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top