By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,686 Members | 2,589 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,686 IT Pros & Developers. It's quick & easy.

AVERAGE from file pls help

P: 9
HI all

Am a newbie in C. I am trying to calculate the average of some numbers (floating point) from a file : the file format is as follows

0 3.312000 3.312000 3.312000
1 3.362000 3.362000 3.362000
2 3.370000 3.370000 3.370000
3 3.340000 3.340000 3.340000

the first column is the index number . the rest 3 columns are same with the same values.

i tried my code . but it went wrong. Any idea is welcomed.
Expand|Select|Wrap|Line Numbers
  1. #include <stdio.h>
  2. #include <math.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5.  
  6. #define N 500   // total number
  7.  
  8. main ()
  9.  
  10. {
  11.     int indx;
  12.     int total =0,count=0;
  13.     float box1,box2,box3, average =0;
  14.     FILE *fp1;
  15.  
  16.     fp1 = fopen ("bxlength.g87","r");
  17.  
  18.     while (fscanf (fp1,"%d%f%f%f",&indx,&box1,&box2,&box3)!=EOF)
  19.  
  20.     {
  21.  
  22.     total+=box1;
  23.     ++count;
  24.  
  25.     }
  26.  
  27.     average =  total/N;
  28.  
  29.         //printf("%d %f %f %f",indx,box1,box2,box3);
  30.  
  31.     printf("%f %f",total,average);
  32.  
  33.  
  34.  
  35.     fclose (fp1);
  36.  
  37.  
  38. }
  39.  
Thanks in adavnce
Jul 9 '07 #1
Share this Question
Share on Google+
2 Replies


weaknessforcats
Expert Mod 5K+
P: 9,197
You are adding only box1 to the total.

average = total/N;


This divides the total by 500 but you don't have 500 numbers.

Fix this and let me know.
Jul 9 '07 #2

P: 67
Also, total is an integer, not really the best idea when averaging floating point numbers. And average is never declared. and should also be floating point.
Jul 9 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.