C++ Primer Plus Chapter 3 Exercise 6

c plus plusThis one could have been harder than it was, but I happen to know the magic number to make this easy, 235.  Here is why 235 is the magic number:

US MPG = 100/E [km/L] x 0.621 [mi/km] x 3.785 [L/US gal] = 235 ÷ E

Where E is Liters per 100km. My solution to exercise 6 is below:

6. Write a program that asks you to enter an automobile gasoline consumption figure in the
European style (liters per 100 kilometers) and converts to the U.S. style of miles per gallon.
Note that in addition to using different units of measurement, the U.S approach
(distance / fuel) is the inverse of the European approach (fuel / distance). Note that 100
kilometers is 62.14 miles, and 1 gallon is 3.875 liters. Thus, 19 mpg is about 12.4 l/100
km, and 27 mpg is about 8.7 l/100 km.

#include <iostream>

using namespace std;

int main()
{
float liters;
int mpg;

cout << "Enter the number of European liters per 100 kilometers to convert: ";
cin >> liters;

// Convert to US mpg
mpg = 235 / liters;
cout << liters << " liters " << " is equal to " <<  mpg << " miles per gallon " << endl;

cin.get();
return 0;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s