25 1450.8 62.0 36 3240.9 136.5 44 1792.6 76.9 52 2360.7 105.1 68 2114.3 67.2 Dec
ID: 3940393 • Letter: 2
Question
25 1450.8 62.0
36 3240.9 136.5
44 1792.6 76.9
52 2360.7 105.1
68 2114.3 67.2
Declare a single structure type suitable for a car record consisting of an integer car identification number, a float value for the miles driven by the car, and a float value for the number of gallons used by each car. Declare a structure variable using this structure type.
Using the structure type declared above, write a C program that loops five times, reading each line of data from the cars.txt file into the members of the structure variable, calculating the mpg for that car, and printing the car number and mpg.
Once the file has been read, the program should display the average miles per gallon achieved by the complete fleet of cars.
Explanation / Answer
// C code
#include <stdio.h>
#include <stdlib.h>
struct Car
{
int car_IN;
float miles;
float gallons;
};
int main ()
{
FILE *infile;
struct Car car[5];
infile = fopen ("cars.txt","r");
if (infile == NULL)
{
fprintf(stderr, " Error opening accounts.dat ");
exit (1);
}
int size = 0;
float sum = 0;
float avg;
while (1)
{
fscanf(infile,"%d",&car[size].car_IN);
fscanf(infile,"%f",&car[size].miles);
fscanf(infile,"%f",&car[size].gallons);
avg = (car[size].miles/car[size].gallons);
printf("Car IN: %d Average: %0.2f mpg ",car[size].car_IN,avg);
sum = sum + avg;
size++;
if(feof(infile))
{
break;
}
}
fclose (infile);
sum = sum/size;
printf(" Average miles per gallon achieved by the complete fleet of cars: %0.2f ",sum);
return 0;
}
/*
output:
Car IN: 25 Average: 23.40 mpg
Car IN: 36 Average: 23.74 mpg
Car IN: 44 Average: 23.31 mpg
Car IN: 52 Average: 22.46 mpg
Car IN: 68 Average: 31.46 mpg
Average miles per gallon achieved by the complete fleet of cars: 24.88
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.