Web site template - 210 Control Structures: Part 2 Chapter 5 Notice
210 Control Structures: Part 2 Chapter 5 Notice that the variables amount, principal and rateare of type double. We did this for simplicity, because we are dealing with fractional parts of dollars and thus need a type that allows decimal points in its values. Unfortunately, this setting can cause trouble. Here is a simple explanation of what can go wrong when using floator double to represent dollar amounts (assuming that dollar amounts are displayed with two digits to the right of the decimal point): Two double dollar amounts stored in the machine could be 14.234 (which would normally be rounded to 14.23 for display purposes) and 18.673 (which would normally be rounded to 18.67 for display purposes). When these amounts are added, they produce the internal sum 32.907, which would normally be rounded to 32.91 for display purposes. Thus, your printout could appear as 14.23 + 18.67 32.91 but a person adding the individual numbers as printed would expect the sum to be 32.90. You have been warned! Good Programming Practice 5.10 Do not use variables of type float or double to perform precise monetary calculations. The imprecision of floating-point numbers can cause errors that will result in incorrect monetary values. In the exercises, we explore the use of integers to perform monetary calculations. [Note: Some third-party vendors provide for-sale class libraries that perform precise monetary calculations.] Note that the body of the forstructure contains the calculation 1.0+rate, which appears as an argument to the Math.pow method. In fact, this calculation produces the same result each time through the loop, so repeating the calculation every iteration of the loop is wasteful. Performance Tip 5.1 Avoid placing expressions whose values do not change inside loops. But even if you do, many of today s sophisticated optimizing compilers will place such expressions outside loops in the generated compiled code. Performance Tip 5.2 Many compilers contain optimization features that improve the code that you write, but it is still better to write good code from the start. 5.5 The switch Multiple-Selection Structure We have discussed the if single-selection structure and the if/else double-selection structure. Occasionally, an algorithm contains a series of decisions in which the algorithm tests a variable or expression separately for each of the constant integral values (i.e., values of types byte, short, int and char) the variable or expression may assume and takes different actions based on those values. Java provides the switch multiple-selection structure to handle such decision making. The applet of Fig. 5.7 demonstrates drawing lines, rectangles or ovals, based on an integer the user inputs via an input dialog. Copyright 1992 2002 by Deitel & Associates, Inc. All Rights Reserved. 7/2/01