Java Reference
In-Depth Information
value into an integer. As described earlier, you can cast a
double
to an
int
, which
will truncate anything after the decimal point:
x = (int) (3.4 * 2.9); // now legal
This statement first evaluates
3.4 * 2.9
to get
9.86
and then truncates that value
to get the integer
9
.
Common Programming Error
Forgetting to Cast
We often write programs that involve a mixture of
int
s and
double
s, so it is easy
to make mistakes when it comes to combinations of the two. For example, sup-
pose that you want to compute the percentage of correctly answered questions on
a student's test, given the total number of questions on the test and the number of
questions the student got right. You might declare the following variables:
int totalQuestions;
int numRight;
double percent;
Suppose the first two are initialized as follows:
totalQuestions = 73;
numRight = 59;
How do you compute the percentage of questions that the student got right?
You divide the number right by the total number of questions and multiply by
100 to turn it into a percentage:
percent = numRight / totalQuestions * 100; // incorrect
Unfortunately, if you print out the value of the variable
percent
after execut-
ing this line of code, you will find that it has the value
0.0
. But obviously the
student got more than 0% correct.
The problem comes from integer division. The expression you are using
begins with two
int
values:
numRight / totalQuestions
which means you are computing
59 / 73
Continued on next page
Search WWH ::
Custom Search