Java Reference
In-Depth Information
A totally fruity program
Average fruit is 7.5
How It Works
The program just computes the average number of fruits of different kinds by dividing the total by 2.0.
As you can see, I have used various representations for the initializing values for the variables in the pro-
gram, 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 Arithmetic Operators
You can use ++ and -- operators 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 an operation of the form:
floatOperand1 % floatOperand2
The result is the floating-point remainder after dividing floatOperand2 into floatOperand1 an integral
number of times. For example, the expression 12.6 % 5.1 gives the result 2.4 (actually 2.4000006 because
decimal values that are not integral do not always have an exact representation as binary floating-point val-
ues). In general, the sign of the result of applying the modulus operator to floating-point values is the sign of
the dividend. The magnitude of the result of a floating-point remainder operation is the largest integral value
such that the magnitude of the result of multiplying the divisor by the result of the remainder operation does
not exceed the dividend.
Error Conditions in Floating-Point Arithmetic
There are two error conditions that can occur with floating-point operations that are signaled by a special
result value being generated. One occurs when a calculation produces a value that is outside the range that
can be represented by the floating-point type you are using, and the other arises when the result is mathem-
atically indeterminate, such as when your calculation is effectively dividing zero by zero.
To illustrate the first kind of error you could use a variable to specify the number of types of fruit. You
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 you happened to set fruitTypes to 0.0, the output from
the program would be the following:
Search WWH ::




Custom Search