UIView alpha value compare error
At first, I set a view's alpha to 0.4, I want to some actions later when aView.alpha == 0.4, but the compare failed.
Code:
aView.alpha = 0.4;
...//开发者_C百科never changes aView.alpha.
if (aView.alpha == 0.4) {
//this compare failed.
}
BUT, when I set the alpha to 0.5, it works!
aView.alpha = 0.5;
...
if (aView.alpha == 0.5) {
//it's OK.
}
Anything wrong?
Never compare floats using equality. It can work (apparently "positive zero" and "negative zero" are exact values) but you need to check that there is a very small difference, not that they are equal. Like:
#define TINY_DELTA (.0001f)
if(fabsf(floatA - floatB) < TINY_DELTA) {
// equal for all intensive porpoises
}
(Actually you have doubles there. In general, use "0.5f" to use floats. It is generally faster on most of the hardware out there.)
精彩评论