It may well be that the default treatment of mixed expressions listed in the preceding section is not what you want. For example, suppose you have defined a double variable result; and two variables, three and two, of type int with the values 3 and 2, respectively. If you compute the value of result with the statement
result = 1.5 + three/two;
the value stored will be 2.5, since three/two will be executed as an integer operation and will produce the result 1. You may have wanted the term three/two to produce the value 1.5 in Java program so the overall result would be 3.0. You could do this using an explicit cast:
result = 1.5 + (double)three/two;
This causes the value stored in three to be converted to type double before the divide operation takes place. Then rule 1 applies for the divide operation, and the operand two is also converted to type double before the divide operation is executed.
No comments:
Post a Comment
Thanks for Commenting......