Monday, June 25, 2018

c - How to read numbers from file and calculate the mean?

I have a list of numbers in my *.txt file:



1 2  
3


called numbers.txt. I need to read them and calculate the mean, for my file it will be: (1 + 2 + 3) / 3 = 2; Although my code shows some wrong results, it read 3 two times. Why is that, how to solve it?



My code:




#include 
#include

double fun(const char *filename)
{
double sum = 0, mean = 0, tmp = 0;
int i = 0;
FILE *f;
if((f = fopen(filename, "r")) == NULL)
{

exit(-1);
}

while(!feof(f))
{
fscanf(f, "%lf", &tmp);
printf("tmp = %f \n", tmp);
sum += tmp;
++ i;
}


i = i - 1;
mean = sum / i;

fclose(f);

printf("i = %d\n", i);
printf("sum = %f\n", sum);
printf("mean = %f\n", mean);


return mean;
}

int main(int argc, char **argv)
{
fun("numbers.txt");

return 0;
}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...