The following program reads all the numbers from the input file values.dat and stores average of these numbers in an output file named as average.res
#include < stdio.h >
#include < conio.h >
main()
{
FILE *fpin, *fpout;
float val, avg, sum=0;
int count=0;
if ((fpin = fopen("values.dat", "r"))== NULL)
/*open the data file for reading purposes*/
printf("\nERROR - cannot open the designated file\n");
else {/*read and display each character from the file*/
while(!feof(fpin)) {
fscanf(fpin, "%f", &val);
sum += val;
count++;
}
}
avg = sum/count;
if ((fpout = fopen("average.res", "w")) == NULL)
/*open the data file for writing purposes*/
printf("\nERROR- cannot open the designated file\n");
else /*write the average in the file*/
fprintf(fpout, "The average of numbers of file values.dat is %.3f\n", avg);
fclose(fpin);
fclose(fout);
getch();
}
If the average value computed is 81.563, then the output line will have the following line
The average of numbers of file values.dat is 81.563
No comments:
Post a Comment