double array don't equate with a constant double

erwin1978

Golden Member
Jun 22, 2001
1,638
3
81
I have a variable of type double. I also have an array of type double that's been initialized. I traverse the array until I find the value that equals the double variable. Somehow the loop will not stop even though I have found the index in the array that contains the value equal that of the variable.

When the program is ran, the value of double variable "displacement" is displayed. The program starts going through the double array. "k" is the index while "bin" represents the value that k points to in the array.
When "k" = 51, "bin" == "displacement." The loop should stop but it doesn't. Why?


File
 

EagleKeeper

Discussion Club Moderator<br>Elite Member
Staff member
Oct 30, 2000
42,589
5
0
Your value (displacement) is coming right in on the boundary that you are testing.
Depending on how rounding is being done, the valued do not match up.

When doing float comparisons, always use a small range to allow for the rounding that may occur.
 

Barnaby W. Füi

Elite Member
Aug 14, 2001
12,343
0
0
Yeah, usually you want to check if the two floats are within a tiny range of each other, not use an equality test.