54.6k views
5 votes
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.

1 Answer

5 votes

Final answer:

The DrivingCost() function calculates the cost of driving given the miles driven, vehicle's fuel efficiency, and gas price. Output formatted to two decimal places is achieved with setprecision(2) in cout statements.

Step-by-step explanation:

The function DrivingCost() calculates the cost of driving a certain number of miles based on the vehicle's fuel efficiency (miles per gallon) and the price of gasoline (dollars per gallon).

Function Definition

double DrivingCost(double drivenMiles, double milesPerGallon, double dollarsPerGallon) {
return (drivenMiles / milesPerGallon) * dollarsPerGallon;
}

Example of Use

When provided with a car that runs 20 miles per gallon and gasoline at $3.1599 per gallon, the cost for driving

  • 10 miles is $1.58,
  • 50 miles is $7.90, and
  • 400 miles is $63.20.

These calculations are made by calling the function

DrivingCost

with the appropriate parameters and returning the cost. Cout statements should use

fixed

and

setprecision(2)

for formatting the output.

User ReFORtEM
by
5.1k points