C++
5.22 LAB: Driving cost - functions
Write a function DrivingCost() with input parameters drivenMiles, milesPerGallon, and dollarsPerGallon, that returns the dollar cost to drive those miles. All items are of type double. If the function is called with 50 20.0 3.1599, the function returns 7.89975.

Define that function in a program whose inputs are the car's miles/gallon and the gas dollars/gallon (both doubles). Output the gas cost for 10 miles, 50 miles, and 400 miles, by calling your DrivingCost function three times.

Output each floating-point value with two digits after the decimal point, which can be achieved by executing
cout << fixed << setprecision(2); once before all other cout statements.

Ex: If the input is:

20.0 3.1599
the output is:

1.58 7.90 63.20
Your program must define and call a function:
double DrivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon)

Respuesta :

Answer:

#include <iostream>

#include<iomanip>

using namespace std;

double DrivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon)

{

  double dollarCost = 0;

  dollarCost = (dollarsPerGallon * drivenMiles) / milesPerGallon;

  return dollarCost;

}

int main()

{

  double miles = 0;

  double dollars = 0;

  cout << "Enter miles per Gallon   : ";

  cin >> miles;

  cout << "Enter dollars per Gallon: ";

  cin >> dollars;

  cout << fixed << setprecision(2);

  cout << endl;

  cout << "Gas cost for 10 miles : " << DrivingCost(10, miles, dollars) << endl;

  cout << "Gas cost for 50 miles : " <<DrivingCost(50, miles, dollars) << endl;

  cout << "Gas cost for 400 miles: "<<DrivingCost(400, miles, dollars) << endl;

  return 0;

}

Explanation:

  • Create a method definition of DrivingCost that accepts  three input double data type parameters drivenMiles,  milesPerGallon, and dollarsPerGallon and returns  the dollar cost to drive those miles .
  • Calculate total dollar cost and store in the variable, dollarCost .
  • Prompt and read the miles and dollars per gallon  as input from the user .
  • Call the DrivingCost function three times  for the output to the gas cost for 10 miles,  50 miles, and 400 miles.

 

Answer:

def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon):

  gallon_used = driven_miles / miles_per_gallon

  cost = gallon_used * dollars_per_gallon  

  return cost  

miles_per_gallon = float(input(""))

dollars_per_gallon = float(input(""))

cost1 = driving_cost(10, miles_per_gallon, dollars_per_gallon)

cost2 = driving_cost(50, miles_per_gallon, dollars_per_gallon)

cost3 = driving_cost(400, miles_per_gallon, dollars_per_gallon)

print("%.2f" % cost1)

print("%.2f" % cost2)

print("%.2f" % cost3)

Explanation:

ACCESS MORE