Chapter 2 C++ Basics
1. Solutions to the Programming Projects:
1. Metric - English units Conversion A metric ton is 35,273.92 ounces. Write a C++ program to read the weight of a box of cereal in ounces then output this weight in metric tons, along with the number of boxes to yield a metric ton of cereal.
Copyright ? 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
1
Savitch
Problem Solving w/ C++, 6e Instructor’s Resource Guide
Chapter 2
Design: To convert 14 ounces (of cereal) to metric tons, we use the 'ratio of units' to tell us whether to divide or multiply:
1 metric tons 14 ounces * * = 0.000397 metric tons 35,273 ounces
The use of units will simplify the determination of whether to divide or to multiply in making a conversion. Notice that ounces/ounce becomes unit-less, so that we are left with metric ton units. The number of ounces will be very, very much larger than the number of metric tons. It is then reasonable to divide the number of ounces by the number of ounces in a metric ton to get the number of metric tons.
2
Copyright ? 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch
Problem Solving w/ C++, 6e Instructor’s Resource Guide
Chapter 2
Now let metricTonsPerBox be the weight of the cereal box in metric tons. Let ouncesPerBox the be the weight of the cereal box in ounces. Then in C++ the formula becomes:
const double ouncesPerMetric_ton = 35272.92;
metricTonsPerBox = ouncesPerBox / ouncesPerMetricTon;
This is metric tons PER BOX, whence the number of BOX(es) PER metric ton should be the reciprocal:
boxesPerMetricTon = 1 / metricTonsPerBox;
3
Copyright ? 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch
Problem Solving w/ C++, 6e Instructor’s Resource Guide
Chapter 2
Once this analysis is made, the code proceeds quickly:
//Purpose: To convert cereal box weight from ounces to
// metric tons to compute number of boxes to make up a // metric ton of cereal.
#include
const double ouncesPerMetricTon = 35272.92;
4
Copyright ? 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley
Savitch
Problem Solving w/ C++, 6e Instructor’s Resource Guide
Chapter 2
int main() {
double ouncesPerBox, metricTonsPerbox,
boxesPerMetricTon; char ans = 'y';
while( 'y' == ans || 'Y' == ans ) {
cout << “enter the weight in ounces of your”
<< “favorite cereal:” < cin >> ouncesPerBox; metricTonsPerbox = ouncesPerBox / ouncesPerMetricTon; 5 Copyright ? 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley