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

C++ Primer Plus Chapter 3 Exercise 5

c plus plusThere really isn’t much to this one. Simple division. Here is what I have:

5. Write a program that asks how many miles you have driven and how many gallons of
gasoline you have used and then reports the miles per gallon your car has gotten. Or, if
you prefer, the program can request distance in kilometers and petrol in liters and then
report the result European style, in liters per 100 kilometers.

#include <iostream>

using namespace std;

int main()
{
int milesDriven;
int gallonsUsed;
int mpg;

cout << "How many miles have you driven: ";
cin >> milesDriven;
cout << "How many gallon of gas have you used: ";
cin >> gallonsUsed;

// Compute here then output
mpg = milesDriven / gallonsUsed;
cout << "You are getting " << mpg << " miles per gallon, what a clunker!" << endl;

cin.get();
return 0;
}