比较目标 C 中的浮点和双精度数据类型 [英] Comparing float and double data types in objective C

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

问题描述

当在 iPhone 应用程序中使用 double 或 float 数据类型时,我遇到了 ">=" 和 "<=" 比较的问题,因为当为变量分配一个小数点后输入的数字时,例如 4.2,比较中使用的 float 或 double 实际上可能有一个值,例如 4.1999998092651367.由于这种差异,诸如>= 4.2"之类的比较是假而不是真.如何避免这个问题?

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?

推荐答案

当一个变量被赋值为一个小数点后输入的数字,例如 4.2,在比较中使用的 float 或 double 实际上可能有一个值,例如 4.1999998092651367

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

可能..具体来说:

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 正是 4.19999980926513671875,但您将其与 双精度文字4.2"进行比较,其值为 4.20000000000000017763568394002504646778106689453125,所以比较失败.相反,如果您与单精度文字4.2f"进行比较:

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

比较成功,因为值完全相等.浮点数很复杂,但它完全是确定性的;为了使其更直观,您可以做的最简单的事情之一就是不要混合精度.如果您正在使用 float,请确保所有文字都以 f 为后缀,以使它们也具有单精度.

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 中的浮点和双精度数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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