Java Reference
In-Depth Information
for(double radius = 1.0; radius <= 2.0; radius += 0.2) {
System.out.println("radius = " + radius + " area = " + Math.PI*radius*radius);
}
This will produce the output:
radius = 1.0 area = 3.141592653589793
radius = 1.2 area = 4.523893421169302
radius = 1.4 area = 6.157521601035994
radius = 1.5999999999999999 area = 8.04247719318987
radius = 1.7999999999999998 area = 10.178760197630927
radius = 1.9999999999999998 area = 12.566370614359169
r 2 with the standard value PI defined in the Math class,
which is 3.14159265358979323846. Although we intended the values of radius to increment from 1.0
to 2.0 in steps of 0.2, they don't quite make it. The value of radius is never exactly 2.0 or any of the
other intermediate values because 0.2 cannot be represented exactly as a binary floating point value. If
you doubt this, and you are prepared to deal with an infinite loop, change the loop to:
The area has been calculated using the formula
π
// BE WARNED - THIS LOOP DOES NOT END
for(double radius = 1.0; radius != 2.0; radius += 0.2) {
System.out.println("radius = " + radius + " area = " + Math.PI*radius*radius);
}
If the value of radius reaches 2.0, the condition radius ! =2.0 will be false and the loop will end,
but unfortunately it doesn't. Its last value before 2 will be approximately 1.999… and the next value will
be something like 2.1999… and so it will never be 2.0. From this we can deduce a golden rule:
Never use tests that depend on an exact value for a floating point variable to control a loop.
Try It Out - The while Loop
We can write the program for summing integers again using the while loop, so you can see how the
loop mechanism differs from the for loop.
public class WhileLoop {
public static void main(String[] args) {
int limit = 20; // Sum from 1 to this value
int sum = 0; // Accumulate sum in this variable
int i = 1; // Loop counter
// Loop from 1 to the value of limit, adding 1 each cycle
while(i <= limit) {
sum += i++; // Add the current value of i to sum
}
System.out.println("sum = " + sum);
}
}
Search WWH ::




Custom Search