9/17/2008
9/17/2008
9/17/2008
9/17/2008
Loop Pitfall – 2a
int result = 0; double cnt = 1.0;
while (cnt <= 10.0){
cnt += 1.0;
result++;
}
System.out.println(result);
1
int result = 0; double cnt = 0.0;
while (cnt <= 1.0){
cnt += 0.1;
result++;
}
System.out.println(result);
2
Using Real Numbers
Loop 1 prints out 10, as expected, but Loop 2 prints out 11. The value 0.1 cannot be stored precisely in computer memory.
10
11
Here's another example of using a double variable as a counter. The two loops are identical in concept, and therefore, should output the same result. They would if real numbers are stored precisely in computer memory. Because the value of 0.1 cannot be represented precisely in computer memory, the second one will actually print out 11, while the first one prints out 10, as expected.