The for loop for(double d = 0.0; d != 1.0; d = d + 0.1) does floating point addition. However as floating point addition is not 100% accurate adding 0.1 10 times gives us a number slightly more than 1.0 (say 1.00000001). The equality condition (1.0 == 1.00000001) fails and the loop continues forever.
Key Learning
With floating point numbers it is better to use the greater-or-equal or less-or-equal operator instead of equality operator i.e. use '<=' or '=>' instead of '=='.
Sorry no correct answers this week!
No comments:
Post a Comment
Solution for this question?