比较目标C float和double数据类型 [英] Comparing float and double data types in objective C

查看:158
本文介绍了比较目标C float和double数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用双或漂浮在一个iPhone应用程序的数据类型,我正在与> =和问题< =比较,因为当一个变量被分配了一个小数位中输入一个数字,如4.2,在比较中使用的浮点或双实际上可以具有诸如4.1999998092651367的值。因为这种差异,如> = 4.2的比较为假,而不是真实的。我怎样才能避免这个问题?


解决方案

  

当变量被分配如4.2与一个小数位输入的数字,在比较中使用的浮动或双实际上可具有一个值,如4.1999998092651367


不是的可以的。 。具体而言:

 浮动F = 4.2; // f是完全相同4.19999980926513671875
双D = 4.2; // d为准确4.20000000000000017763568394002504646778106689453125

问题是当你写的是这样的:

 浮动F = 4.2;
如果(F> = 4.2){
    //不执行code此块。
}

˚F恰好 4.19999980926513671875 ,但是你把它比作在双击precision文字4.2,其值为 4.20000000000000017763568394002504646778106689453125 ,所以比较失败。相反,如果你比较针对单个precision文字4.2f

 浮动F = 4.2;
如果(F> = 4.2f){
    // code这个块exectued。
}

比较成功,因为这些值完全相等。浮点是复杂的,但它是完全确定的;你可以做,使之更加直观最简单的事情之一,就是不能混用precisions。如果你使用浮动工作,确保所有文字都与后缀˚F来使他们的单precision了。

(这也可以提高性能,但是这不这样做的原因,这样做是因为它会让你的code更正确的原因)。

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?

解决方案

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).

这篇关于比较目标C float和double数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆