IRM - Chapter - 6e - 02

2019-04-23 19:55

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 using namespace std;

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


IRM - Chapter - 6e - 02.doc 将本文的Word文档下载到电脑 下载失败或者文档不完整,请联系客服人员解决!

下一篇:李春城案

相关阅读
本类排行
× 注册会员免费下载(下载后可以自由复制和排版)

马上注册会员

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信: QQ: