Print Friendly and PDF
a) Read the problem statement. b) Formulate the algorithm using pseudocode and top­down, stepwise refinement. c) Write a C++ program. d) Test, debug and execute the C++ program. 4.1 3 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track
a) Read the problem statement.
b) Formulate the algorithm using pseudocode and top down, stepwise refinement.
c) Write a C++ program.
d) Test, debug and execute the C++ program. 4.1 3 (Gas Mileage) Drivers are concerned with the mileage obtained by their automobiles. One driver has kept track of several trips by recording miles driven and gallons used for each trip. 


Develop a C++ program that uses a while statement to input the miles driven and gallons used for each trip. 

The program should calculate and display the miles per gallon obtained for each trip and print the combined miles per gallon obtained for all tankfuls up to this point.

Enter miles driven (­1 to quit): 287
Enter gallons used: 1 3
MPG this trip: 22.076923
Total MPG: 22.076923
Enter miles driven (­1 to quit): 200
Enter gallons used: 1 0
MPG this trip: 20.000000
Total MPG: 21 .1 7391 3
Enter the miles driven (­1 to quit): 1 20
Enter gallons used: 5
MPG this trip: 24.000000
Total MPG: 21 .678571
Enter the miles used (­1 to quit): ­1

Solution:


#include <cstdlib >
#include <iostream >
#include <iomanip >
using namespace std;
int main()
{
//variable declarations
int totalMiles = 0;
int totalGallons = 0;
int miles;
int gallons;
cout << "\nEnter miles driven (‐1 to quit) : ";
cin >> miles; //trip miles input
while( miles ! = 1 ) //loops till user enter ‐1
{
cout << "Enter gallons used: ";
cin >> gallons; //used gallons input
//total miles and gallons calculation
totalMiles += miles;
totalGallons += gallons;
//mpg declarations
double thisMPG;
double totalMPG;
//format
thisMPG = static_cast< double > ( miles ) / gallons;
totalMPG = static_cast< double > ( totalMiles ) / totalGallons;
//output
cout << "MPG this trip: " << setprecision( 6 ) << fixed << thisMPG << endl;
cout << "Total MPG: " << totalMPG << endl;
cout << "\nEnter miles driven (‐1 to quit) : ";
cin >> miles; //trip miles input
}

//for pause
system("PAUSE") ;
return 0;
}
zubairsaif

Zubair saif

A passionate writer who loves to write on new technology and programming

Post A Comment:

1 comments: