Chapter 2 – Q #11: Distance per Tank – Tony Gaddis – Starting Out With C++
Problem: -
A car with a 20-gallon gas tank averages 21.5 miles per gallon when driven in town and 26.8 miles per gallon when driven on the highway. Write a program that calculates and displays the distance the car can travel on one tank of gas when driven in town and when driven on the highway.
Hint: The following formula can be used to calculate the distance:
Distance = Number of Gallons * Average Miles per Gallon
Solution: -
#include <iostream>
using namespace std;
int main()
{
float no_of_gallon = 20;
float miles_in_town = 21.5;
float miles_in_highway = 26.8;
float average = 0.0, distance;
average = (miles_in_town + miles_in_highway) / 2.0;
distance = no_of_gallon * average;
cout << "Distance is " << distance;
return 0;
}
This is the solution of this question
OUTPUT OF THIS QUESTION
Explanation of this Solution
- I declared three float variables and initialize given values.
- I declared another two float variables named average and distance.
- Calculate average of gallons and store average variable.
- Them, calculate distance by using given formula and store distance variable.
- In last, display output of distance on the screen.
- Return 0 to the main function.
Also, I attach CPP file of this problem. You can download this file
0 Comments