Thread: max/min in a list of numbers

  1. #1
    Registered User
    Join Date
    May 2005
    Posts
    1

    max/min in a list of numbers

    I am having trouble finding the min and max in a list. I set up a run function so that it does not repalce the number with the next number in the list. Here is what I have and it will compile but the min and max use the number -999.

    Code:
    #include <stdio.h>
    int factorial (int number);
    int main ()
    {
            int count = 0, run = 1;
            double number, sum, average, min, max;
            sum = 0;
            printf ("Please enter the numbers. Enter -999 when done.\n");
            while (number != -999)
            {
             scanf ("%lf", &number);
             if (number != -999)
             {
              sum += number;
              count++;
              }
            }
            if (count != 0)
             {
             average = sum/count;
             if (run == 1) {
    max=number;
    min=number;
    
    run=0;
    }
    if (number<min)
    min=number;
    if (number>max)
    max=number;
    count += 1;
    
             printf ("The sum of the given list of number is %f.\n", sum);
             printf ("The average of the given list of numbers is %f.\n", average);
             printf ("The maximum number in the list is %f.\n", max);

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Quote Originally Posted by shockalaca
    Here is what I have and it will compile
    Not here; why not copy and paste the code you are discussing? Also, try searching this forum.
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    May 2005
    Posts
    4
    Of course it does. You are exiting the while far too early.It's the way you put the { }

    Code:
            while (number != -999)
            {
             scanf ("%lf", &number);
             if (number != -999)
                {
                  sum += number;
                  count++;
                }
            } //here you exit the while ; when you do so number is  -999
               //but sum and count are calculated correctly
    also may i sugest using do ...while sintax wich is appropiate here and dumping run and sum:
    Use count to initialize min and max and use average to acumulate the numbers then:
    average = average/count;

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 26
    Last Post: 07-05-2010, 10:43 AM
  2. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. 1st Class LIST ADT
    By Unregistered in forum C++ Programming
    Replies: 1
    Last Post: 11-09-2001, 07:29 PM