Friday, 23 September 2016

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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...