开发者

Absolute value isn't working

My iPhone has a line of code that looks like this:

double decimal2 = abs(newLocation.coordinate.longitude - degrees);

I'm trying to ensure that the value of decimal2 is开发者_StackOverflow always positive. However, decimal2 is currently -82.

Can anyone explain this? I'm not doing anything else to the value of decimal2.

Thanks.


would suggest you to use NSDecimalNumber

You could use the built-in functions of the NSDecimalNumber class to compare the number to zero, then multiply by -1 as appropriate. For example:

- (NSDecimalNumber *)abs:(NSDecimalNumber *)num {
    if [myNumber compare:[NSDecimalNumber zero]] == NSOrderedAscending) {
        // Number is negative. Multiply by -1
        NSDecimalNumber * negativeOne = [NSDecimalNumber decimalNumberWithMantissa:1
                                                                          exponent:0
                                                                        isNegative:YES];
        return [num decimalNumberByMultiplyingBy:negativeOne];
    } else {
        return num;
    }
}

in this case , there's no loss of precision


Perhaps this "abs" function isn't what you think it is. Are you sure you know where it's coming from? Maybe you or someone else has defined your own? There's no reason why a valid "abs" function would do this.


You're using the abs() function, which returns int, but assigning the result to a double. You should either assign the result to a variable of type int, or use a version of the absolute value function that returns double: double fabs(double).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜