Thread: Average of numbers in a file

  1. #1
    Registered User
    Join Date
    Dec 2011
    Posts
    1

    Average of numbers in a file

    I am writing a program that will read in an unknown amount of integers and print the average of them. I can't seem to figure out why this won't work.
    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(int argc, char *argv[]){
     
     int n, amount = 1, sum = 0, average;
     FILE *fin = fopen(argv[1], "r");
     
     while(fscanf(fin,"%d",&n) != EOF){
         fscanf(fin,"%d",&n);
         sum += n;
         amount++;
      }
    
     average = sum/amount;
    
      printf("%d", average);
    
     fclose(fin);
     return 0;
    }
    The file is
    Code:
    2 2
    I wrote some test code to print out the sum and amount after the while loop and it printed out 2 2.

    EDIT: Nevermind, when i set amount back to 0 it worked. Strange because the first time i had it equal to 0 it didn't work but oh well.
    Last edited by starghost3; 12-14-2011 at 03:01 PM. Reason: fixed my problem

  2. #2
    Registered User TheBigH's Avatar
    Join Date
    May 2010
    Location
    Melbourne, Australia
    Posts
    426
    What if your numbers are 1,5,10?

    The average of those is 16/3=5.3333333.

    Your "average" variable should not be an integer, it should be a float, and you should do floating point division on "sum" and "amount"
    Code:
    while(!asleep) {
       sheep++;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. find & print the average of the odd numbers
    By zozo995 in forum C++ Programming
    Replies: 1
    Last Post: 10-27-2010, 10:31 PM
  2. help in finding average of a class of numbers
    By hastefan2001 in forum C++ Programming
    Replies: 7
    Last Post: 06-29-2009, 01:11 PM
  3. Average of n numbers
    By anirban in forum Tech Board
    Replies: 2
    Last Post: 07-16-2008, 10:57 PM
  4. Newbie : Getting the average of 3 numbers
    By Swerve in forum C++ Programming
    Replies: 10
    Last Post: 08-27-2007, 05:02 PM
  5. Replies: 4
    Last Post: 03-03-2003, 03:52 PM