Objective-c中的pow函数

Rah*_*tel -2 math objective-c pow ios

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

我想解决下面的数学问题

  100 *(0.0548/360*3+powf(1+0.0533, 3/12)/powf(1+0.0548, 3/12)) 
Run Code Online (Sandbox Code Playgroud)

对于相同的数学,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)
Run Code Online (Sandbox Code Playgroud)

现在众所周知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)
Run Code Online (Sandbox Code Playgroud)

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

pax*_*blo 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;
}
Run Code Online (Sandbox Code Playgroud)

输出是(注释):

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.
Run Code Online (Sandbox Code Playgroud)

  • 这与iOS无关.它与编译器完成的整数处理有关.数字文字3和12被视为整数,因此3/12是整数除法,其结果为0. (2认同)