Chapter 2 – Q #11: Distance per Tank – Tony Gaddis – Starting Out With C++

Chapter 2 – Q #11:  Distance per Tank – Tony Gaddis – Starting Out With C++






Distance per Tank


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

Output


Explanation of this Solution


  1. I declared three float variables and initialize given values.
  2. I declared another two float variables named average and distance.
  3. Calculate average of gallons and store average variable.
  4. Them, calculate distance by using given formula and store distance variable.
  5. In last, display output of distance on the screen.
  6. Return 0 to the main function.

Also, I attach CPP file of this problem. You can download this file

Click Here to Download This File

Post a Comment

0 Comments