Objective-c中的pow函数

时间:2014-02-28 14:20:20

标签: ios objective-c math pow

我正在Objective-C中实现数学计算,其中我使用了pow(<#double#>, <#double#>)函数,但它表现得很奇怪。

我正在尝试解决下面的数学

  100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)) 

对于相同的数学,excel和xcode的结果是不同的。

 Excel output = 100.01001 (correct)
 NSLog(@"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)));
 Xcode output = 100.045667 (wrong)

现在大家都知道 3/12 = 0.25  当我替换 * 3/12 *与上面的数学中的 0.25 时,xcode会返回如下所示的真实结果

 Excel output = 100.01001 (correct)
 NSLog(@"-->%f",100 *(0.0548/360*3+powf(1+0.0533, 0.25)/powf(1+0.0548, 0.25)));
 Xcode output = 100.010095 (correct)

任何人都知道为什么pow函数表现得像这样奇怪?
注意:我还使用了powf,但行为仍然相同。

1 个答案:

答案 0 :(得分:10)

当您执行整数数学时,

3/12为零。在C,C ++,ObjC和Java等语言中,只包含整数的x / y这样的表达式为您提供了一个整数结果,而不是一个浮点结果。

我建议您尝试使用3.0/12.0

以下C程序(在这种情况下与ObjC相同的行为)显示了这一点:

#include <stdio.h>
#include <math.h>
int main (void) {
    // Integer math.

    double d = 100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12));
    printf ("%lf\n", d);

    // Just using zero as the power.

    d = 100 *(0.0548/360*3+powf(1+0.0533, 0)/powf(1+0.0548, 0));
    printf ("%lf\n", d);

    // Using a floating point power.

    d = 100 *(0.0548/360*3+powf(1+0.0533, 3.0/12.0)/powf(1+0.0548, 3.0/12.0));
    printf ("%lf\n", d);

    return 0;
}

输出是(注释):

100.045667 <= integer math gives wrong answer.
100.045667 <= the same as if you simply used 0 as the power.
100.010095 <= however, floating point power is okay.
相关问题