25 14508 620 36 32409 1365 44 17926 769 52 23607 1051 68 211
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.
Solution
// 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\\tAverage: %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
*/

