Java Reference
In-Depth Information
This will produce the output:
A totally fruity program
Average fruit is 7.5
The program just computes the average number of fruits by dividing the total by 2.0.
As you can see, we have used various representations for the initializing values for the
variables in the program, which are now of type double . It's not the ideal way to
write 5.0 but at least it demonstrates that you can write a negative exponent value.
Other Floating Point Operators
You can use ++ and -- with floating point variables, and they have the same effect as with integer variables,
incrementing or decrementing the floating point variable to which they are applied by 1.0. You can use them
in prefix or postfix form, and their operation in each case is the same as with integer variables.
You can apply the modulus operator, % , to floating point values too. For the operation.
floatOperand1 % floatOperand2
the result will be the floating point remainder after dividing floatOperand2 into floatOperand1
an integral number of times. For example, the expression 12.6 % 5.1 will give the result 2.4 .
Error Conditions in Floating Point Arithmetic
There are two error conditions that are signaled by a special result value being generated. One occurs
when a calculation produces a value which is outside the range that can be represented, and the other
arises when the result is mathematically indeterminate, such as when your calculation is effectively
dividing zero by zero.
To illustrate the first kind of error we could use a variable to specify the number of types of fruit. We
could define the variable:
double fruitTypes = 2.0;
and then rewrite the calculation as:
averageFruit = (numOranges + numApples) / fruitTypes;
This in itself is not particularly interesting, but if we happened to set fruitTypes to 0.0, the output
from the program would be:
A totally fruity program
Average fruit is Infinity
Search WWH ::




Custom Search