Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

iphone - Comparing float and double data types in objective C

When using double or float data type in an iPhone app, I am running into problems with ">=" and "<=" comparisons because when a variable is assigned a number entered with one decimal place, such as 4.2, the float or double used in the comparison actually may have a value such as 4.1999998092651367. Because of this difference, a comparison such as ">= 4.2" is false instead of true. How can I avoid this problem?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

when a variable is assigned a number entered with one decimal place, such as 4.2, the float or double used in the comparison actually may have a value such as 4.1999998092651367

Not may. will. To be specific:

float f = 4.2;  // f is exactly 4.19999980926513671875
double d = 4.2; // d is exactly 4.20000000000000017763568394002504646778106689453125

The problem comes when you write something like:

float f = 4.2;
if (f >= 4.2) {
    // this block of code is not executed.
}

f is exactly 4.19999980926513671875, but you're comparing it to the double-precision literal "4.2", which has the value 4.20000000000000017763568394002504646778106689453125, so the comparison fails. If instead you compare against the single precision literal "4.2f":

float f = 4.2;
if (f >= 4.2f) {
    // this block of code is exectued.
}

the comparison succeeds, because the values are exactly equal. Floating-point is complicated, but it is entirely deterministic; one of the simplest things you can do to make it more intuitive is to not mix precisions. If you're working with float, make sure all of your literals are suffixed with f to make them single precision, too.

(This can also improve performance, but that's not the reason to do it; the reason to do it is because it will make your code more correct).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...