Added exercise 4.28
[Cpp-Deitel-Exercises.git] / Chapter-4 / 4-13.cpp
blobc199e908bb00347eefe1dda92eeb546baf8ce215
1 /*C++ How to Program, 9/E, by Paul Deitel & Harvey Deitel.
3 Solution of exercise 4.13:
4 (Gas Mileage) Drivers are concerned with the mileage obtained by their
5 automobiles. One driver has kept track of several trips by recording miles
6 driven and gallons used for each trip. Develop a C++ program that uses a while
7 statement to input the miles driven and gallons used for each trip. The
8 program should calculate and display the miles per gallon obtained for each
9 trip and print the combined miles per gallon obtained for all tankfuls up to
10 this point.
12 Enter miles driven (-1 to quit): 287
13 Enter gallons used: 13
14 MPG this trip: 22.076923
15 Total MPG: 22.076923
17 Enter miles driven (-1 to quit): 200
18 Enter gallons used: 10
19 MPG this trip: 20.000000
20 Total MPG: 21.173913
22 Enter the miles driven (-1 to quit): 120
23 Enter gallons used: 5
24 MPG this trip: 24.000000
25 Total MPG: 21.678571
27 Enter the miles used (-1 to quit): -1
29 Written by Juan Carlos Moreno (jcmhsoftware@gmail.com), 2023-01-16.*/
31 #include <iostream>
32 #include <iomanip>
34 using namespace std;
36 int main()
38 double miles; //Miles driven for each trip
39 double gallons; //Gallons used for each trip
40 double total_miles = 0; //Miles driven for all trips
41 double total_gallons = 0; //Gallons used for all trips
43 while (miles != -1)
45 cout << "Enter miles driven (-1 to quit): ";
46 cin >> miles;
48 if (miles != -1)
50 cout << "Enter gallons used: ";
51 cin >> gallons;
52 total_gallons += gallons;
53 total_miles += miles;
54 cout << setprecision(6) << fixed;
55 cout << "MPG this trip: " << miles/gallons << endl;
56 cout << "Total MPG: " << total_miles/total_gallons
57 << endl << endl;
61 return 0;