< previous page page_115 next page >

Page 115
(text box continued from previous page)
Need we say more?
Appendix F talks about programming style. Use it as a guide when you are writing programs.

Problem-Solving Case Study Map Measurements
0115-01.gif
Problem: You're spending a day in the city. You plan to visit the natural history museum, a record store, a gallery, and a bookshop, and then go to a concert. You have a tourist map that shows where these places are located. You want to determine how far apart they are and how far you'll walk during the entire day. Then you can decide when it would be better to take a taxi. According to the map's legend, one inch on the map equals one quarter of a mile on the ground.
Output: The distance between each of the places and the total distance, rounded to the nearest tenth of a mile. The values on which the calculations are based also should be printed for verification purposes.
Discussion: You can measure the distances between two points on the map with a ruler. The program must output miles, so you need to multiply the number of inches by 0.25. You then write down the figure, rounded to the nearest tenth of a mile. When you've done this for each pair of places, you add the distances to get the total mileage. This is essentially the algorithm we use in the program.
The only tricky part is how to round a value to the nearest tenth of a mile. In the last chapter, we showed how to round a floating point value to the nearest integer by adding 0.5 and using a type cast to truncate the result:
int(floatValue + 0.5)
To round to the nearest tenth, we first multiply the value by 10, round the result to the nearest integer, and then divide by 10 again. For example, if floatValue contains 5.162, then
float(int(floatValue * 10.0 + 0.5)) / 10.0
gives 5.2 as its result.

 
< previous page page_115 next page >