Please help..... A litter is 0.264179 gallons. Write a program that will read in
ID: 3690501 • Letter: P
Question
Please help.....
A litter is 0.264179 gallons. Write a program that will read in the number of liters of gasoline consumed by the user’s car and the number of miles traveled by the car and will then output the number of miles per gallon the car delivered. Your program should allow the user to repeat this calculation as often as the user wishes. Define a function to compute the number of miles per gallon. Your program should use a globally defined constant for the number of liters per gallon.
Hint: Use a do-while loop to repeat the calculation, which asks user to repeat or not at the end of the loop.
Hint: The function should accept two double parameter values – litter and mile values. It returns a double value of miles per gallon.
Explanation / Answer
#include <iostream>
using namespace std ;
const double gallonsPerLiter = 0.264179 ;
const double litersPerGallon = 1 / gallonsPerLiter ;
double GetLiters() ;
double GetMiles() ;
double CalcMPG(double, double) ;
void GiveResults(double, double, double) ;
bool UserWantsToContinue() ;
int main ()
{
double liters, miles, mpg ;
do
{
liters = GetLiters() ;
miles = GetMiles() ;
mpg = CalcMPG(liters, miles) ;
GiveResults(liters, miles, mpg) ;
} while (UserWantsToContinue() ) ;
cout << endl ;
return 0;
}
double GetLiters()
{
int liters ;
cout << " How many liters of gas did you use on your trip? " ;
cin >> liters ;
return liters ;
}
double GetMiles()
{
int miles ;
cout << "How many miles did you travel on your trip? " ;
cin >> miles ;
return miles ;
}
double CalcMPG(double liter_val, double miles_val)
{
return (miles_val / liter_val) * litersPerGallon ;
}
void GiveResults(double liters_GR, double miles_GR, double mpg_GR )
{
cout.setf(ios::fixed ) ;
cout.setf(ios::showpoint ) ;
cout.precision(2) ;
cout << " You travelled " << miles_GR << " miles "
<< "and used " << liters_GR << " liters of gas "
<< "(" << liters_GR * gallonsPerLiter << " gallons). "
<< "Your mileage was " << mpg_GR << " miles per gallon. " ;
}
bool UserWantsToContinue()
{
char answer ;
cout << "Would you like to compute mileage for another trip? (y/n): " ;
cin >> answer ;
if (answer == 'y') return true ;
else return false ;
}