在Objective-C中转换为绝对值 [英] Convert to absolute value in Objective-C
问题描述
如何在Objective-C中将负数转换为绝对值?
How do I convert a negative number to an absolute value in Objective-C?
即
-10
成为
10?
推荐答案
根据变量的类型,abs(int)
,labs(long)
,llabs(long long)
,imaxabs(intmax_t)
,fabsf(float)
,fabs(double)
之一或fabsl(long double)
.
Depending on the type of your variable, one of abs(int)
, labs(long)
, llabs(long long)
, imaxabs(intmax_t)
, fabsf(float)
, fabs(double)
, or fabsl(long double)
.
这些函数都是C标准库的一部分,因此在Objective-C和普通C中都存在(并且通常在C ++程序中也可用).
Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)
(las,没有habs(short)
功能.或者scabs(signed char)
就这样...)
(Alas, there is no habs(short)
function. Or scabs(signed char)
for that matter...)
Apple和GNU的Objective-C标头还包含一个与类型无关的ABS()
宏.我不建议使用ABS()
,但是不能保证它是副作用安全的.例如,ABS(a++)
将具有未定义的结果.
Apple's and GNU's Objective-C headers also include an ABS()
macro which is type-agnostic. I don't recommend using ABS()
however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++)
will have an undefined result.
如果使用的是C ++或Objective-C ++,则可以引入<cmath>
标头并使用std::abs()
,它是所有标准整数和浮点类型的模板.
If you're using C++ or Objective-C++, you can bring in the <cmath>
header and use std::abs()
, which is templated for all the standard integer and floating-point types.
这篇关于在Objective-C中转换为绝对值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!