Java Reference
In-Depth Information
PITFALL: Division with Whole Numbers
When you use the division operator / on two integers, the result is an integer. This
can be a problem if you expect a fraction. Moreover, the problem can easily go
unnoticed, resulting in a program that looks fine but is producing incorrect output
without you even being aware of the problem. For example, suppose you are a
landscape architect who charges $5,000 per mile to landscape a highway, and suppose
you know the length in feet of the highway you are working on. The price you charge
can easily be calculated by the following Java statement:
totalPrice = 5000 * (feet / 5280.0);
This works because there are 5,280 feet in a mile. If the stretch of highway you are
landscaping is 15,000 feet long, this formula will tell you that the total price is
5000 * (15000 / 5280.0)
Your Java program obtains the fi nal value as follows: 15000/5280.0 is computed as
2.84 . Then, the program multiplies 5000 by 2.84 to produce the value 14200.00 . With
the aid of your Java program, you know that you should charge $14,200 for the project.
Now suppose the variable feet is of type int , and you forget to put in the decimal
point and the zero, so that the assignment statement in your program reads as follows:
totalPrice = 5000 * (feet / 5280);
It still looks fi ne, but will cause serious problems. If you use this second form of
the assignment statement, you are dividing two values of type int , so the result of the
division feet/5280 is 15000/5280 , which is the int value 2 (instead of the value 2.84 ,
which you think you are getting). So the value assigned to totalPrice is 5000*2 , or
10000.00 . If you forget the decimal point, you will charge $10,000. However, as we
have already seen, the correct value is $14,200. A missing decimal point has cost you
$4,200. Note that this will be true whether the type of totalPrice is int or double ;
the damage is done before the value is assigned to totalPrice .
Self-Test Exercises
17. Convert each of the following mathematical formulas to a Java expression:
x
+
y
3 x
+
y
+
3 x 3 x
y
7
z
+
2
18. What is the output of the following program lines?
double number = (1/3) * 3;
System.out.println("(1/3) * 3 is equal to " + number);
 
Search WWH ::




Custom Search