Question

Write a program to read the contents of data.txt file, and determine the smallest value (min),...

Write a program to read the contents of data.txt file, and determine the smallest value (min), largest value (max), and the average value (ave). The minimum, maximum, and average values must be calculated in the function calc(). Remember to declare the stdlib.h library, so that you can use the atof function, which will convert the number in the text file into float number. Also, remember to check if there is an error opening the file or not. If there is an error, then return a value of 1 from the function calc(), otherwise return 0 is everything is fine. Open a new text file and save it as data.txt. You must type the 10 numbers below into data.txt. Do NOT save the numbers into an array in the program. The numbers must be processed as the data.txt file is read line-by-line. 0.42 0.94 0.17 0.04 0.68 0.95 0.89 0.18 0.72 0.23 The expected output is Min = 0.040000 Max = 0.950000 Average = 0.522000

0 0
Add a comment Improve this question Transcribed image text
Answer #1

Program:

#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>

int calc(void)
{
FILE *fp;
char line[10];
float min;
float max;
float ave;
float number;
int count=0;

fp = fopen("data.txt", "r"); //opening file
if(fp)
{
if(fgets(line, 10, fp))
{
count++;
number = atof(line); //reading the number
max = number;
min = number;
ave += number;
}
while( fgets(line, 10, fp) )
{
count++;
number = atof(line); //reading the number
if( number > max )
max = number;
else if( number < min )
min = number;

ave += number; //getting sum
}
printf("Min = %f\n", min);
printf("Max = %f\n", max);
printf("Average = %f\n", ave/count);
fclose(fp);
return 0;
}
else
return 1;
}

int main()
{
calc();
return 0;
}

Execution and Output:

Add a comment
Know the answer?
Add Answer to:
Write a program to read the contents of data.txt file, and determine the smallest value (min),...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT