125,904 views
4 votes
4 votes
Driving is expensive. Write a program with a car's miles/gallon and gas dollars/gallon (both doubles) as input, and output the gas cost for 20 miles, 75 miles, and 500 miles. 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.

User Adam Bardon
by
2.4k points

1 Answer

17 votes
17 votes

Answer:

Step-by-step explanation:

The following is written in C++ and asks the user for inputs in both miles/gallon and dollars/gallon and then calculates the gas cost for the requested mileages using the input values

#include <iostream>

#include <iomanip>

using namespace std;

int main () {

// distance in miles

float distance1 = 20.0, distance2 = 75.0, distance3 = 500.0;

float miles_gallon, dollars_gallon;

cout << "Enter cars miles/gallon: "; cin >> miles_gallon;

cout << "Enter cars dollars/gallon: "; cin >> dollars_gallon;

cout << "the gas cost for " << distance1 << " miles is " << fixed << setprecision(2) << (float) dollars_gallon * distance1 / miles_gallon << "$\\";

cout << "the gas cost for " << distance2 << " miles is " << fixed << setprecision(2) << (float) dollars_gallon * distance2 / miles_gallon << "$\\";

cout << "the gas cost for " << distance3 << " miles is " << fixed << setprecision(2) << (float) dollars_gallon * distance3 / miles_gallon << "$\\";

return 0;

}

User Volkerschulz
by
2.6k points