简体   繁体   English

取 CGFloat 的绝对值

[英]taking absolute value of CGFloat

How can I do that?我怎样才能做到这一点? I tried the abs() but it only works for int's.我试过 abs() 但它只适用于 int 的。 Is there a built in way to do so?有没有内置的方法来做到这一点?

CGFloat flo = -123;
abs(flo)

this returns 0这将返回 0

Use fabs()使用 fabs()

CGFloat f = -123.4f;
CGFloat g = fabs(f);

CGFloat is defined as a double on 64-bit machines, and float on 32-bit machines. CGFloat在 64 位机器上被定义为double float在 32 位机器上被定义为float If you are targeting both 64 and 32 bit than this answer gets more complicated, but is still correct.如果您同时针对 64 位和 32 位,则此答案会变得更加复杂,但仍然是正确的。

You want to use fabs() because it works on double datatypes which are larger than float .您想使用fabs()因为它适用于大于float double数据类型。 On 32-bit, assigning the return value of fabs() (which is a double ) into a CGFloat (which is a float ) is ok ONLY if you are taking the absolute value of a CGFloat or float .在 32 位上,仅当您采用CGFloatfloat的绝对值时,才可以将fabs() (这是一个double )的返回值分配给一个CGFloat (这是一个float )。 You would potentially overflow a 32-bit CGFloat if you try to store the absolute value of a large double number.如果您尝试存储大double数的绝对值,您可能会溢出 32 位CGFloat In short, 64-bit is fine, and on 32-bit don't mix and match double and CGFloat and you'll be fine.简而言之,64 位很好,在 32 位上不要混合和匹配doubleCGFloat ,你会没事的。

The ABS() macro apparently can have side-effects on some compilers. ABS()宏显然会对某些编译器产生副作用。

For 64/32 bit system对于 64/32 位系统

#if CGFLOAT_IS_DOUBLE
    CGFloat g = fabs(flo);
#else
    CGFloat g = fabsf(flo);
#endif

I normally just use the ABS macro, as far as I can tell, it works regardless of which system you're on or which primitive you're using.我通常只使用 ABS 宏,据我所知,无论您使用哪个系统或使用哪个原语,它都可以工作。

CGFloat x = -1.1;
double y = -2.1;
NSInteger z = -5;

x = ABS(x);
y = ABS(y);
z = ABS(z);

Small addition:小补充:

CGFloat g = fabs(f);

This will result in a casting warning, because fabs() returns a double value.这将导致强制转换警告,因为 fabs() 返回一个双精度值。 To get a float value back, you need to use fabsf().要返回浮点值,您需要使用 fabsf()。

CGFloat g = fabsf(f);

fabs is depreciated. fabs贬值了。 The signature of abs is now generic with this signature abs的签名现在与此签名通用

/// Returns the absolute value of the given number.
///
/// The absolute value of `x` must be representable in the same type. In
/// particular, the absolute value of a signed, fixed-width integer type's
/// minimum cannot be represented.
///
///     let x = Int8.min
///     // x == -128
///     let y = abs(x)
///     // Overflow error
///
/// - Parameter x: A signed number.
/// - Returns: The absolute value of `x`.
@inlinable public func abs<T>(_ x: T) -> T where T : Comparable, T : SignedNumeric

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM