Thread: Averaging numbers in a while loop?

  1. #1
    Registered User
    Join Date
    Sep 2011
    Posts
    28

    Averaging numbers in a while loop?

    I had to write a program that opens a file, reads a list of doubles, and then averages them. The result SHOULD be 40 something (i don't remember exactly and don't have time to average them again atm), and it's coming out as only 2.1. I do not understand why? Here is my code.

    Code:
    # include <stdio.h>
    
    int main()
    {
            char filename[50];
            double numbers;
    
            printf ("Please enter the file that you wish to open: ");
            scanf("%s", filename);
    
            FILE *infile=fopen(filename, "r");
            if(infile==NULL)
            {
                    printf( "The file was not successfully opened");
            }
    
    
            int i = 0;
            double average;
            while (fscanf(infile, "%lf", &numbers)!=EOF)
            {
                    average+= numbers;
                    i++;
    
                    numbers = numbers/i;
            }
    
            printf("The average is %.2lf\n", numbers);
            fclose(infile);
    
            return 0;
    }
    ....and here is my doubles file
    Code:
    30.9
    10.2
    13.7
    46.1
    50.0
    5.2
    89.3
    77.9
    30.4
    22.0
    100.8
    55.6
    31.8
    60.4
    26.8
    10.1
    99.9
    76.8
    59.6
    40.3
    Thank you for any help!
    Last edited by Chinnie15; 12-01-2011 at 04:08 PM.

  2. #2
    Registered User
    Join Date
    Nov 2011
    Location
    Saratoga, California, USA
    Posts
    334
    Hmm. 40.3 / 19 = 2.1

    Pay attention to your variables and how you calculate an average.

    "total" might be a better name for your accumulator variable.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    General run of thumb on calculating average in a program: calculate the sum in the loop; calculate the average after the loop.

    Tim S.

  4. #4
    Registered User
    Join Date
    Sep 2011
    Posts
    28
    Thank you! I got it!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Array problem averaging numbers
    By Thedon in forum C Programming
    Replies: 6
    Last Post: 10-27-2011, 11:27 AM
  2. Replies: 2
    Last Post: 12-06-2010, 07:03 PM
  3. How to for() loop with hex numbers?
    By monk64 in forum C Programming
    Replies: 5
    Last Post: 04-08-2010, 11:25 PM
  4. averaging numbers?
    By rock4christ in forum C Programming
    Replies: 12
    Last Post: 09-09-2006, 06:38 PM
  5. averaging random numbers
    By Unregistered in forum C Programming
    Replies: 7
    Last Post: 10-27-2001, 03:48 PM