Strange behaviour of the pow function

后端 未结 5 584
借酒劲吻你
借酒劲吻你 2020-11-22 12:23

While running the following lines of code:

int i,a;    

for(i=0;i<=4;i++)  
{    
    a=pow(10,i);    
    printf(\"%d\\t\",a);    
}   
相关标签:
5条回答
  • 2020-11-22 12:51

    Mathematically, the integer power of an integer is an integer.

    In a good quality pow() routine this specific calculation should NOT produce any round-off errors. I ran your code on Eclipse/Microsoft C and got the following output:

    1   10  100 1000    10000   
    

    This test does NOT indicate if Microsoft is using floats and rounding or if they are detecting the type of your numbers and choosing the appropriate method.

    So, I ran the following code:

    #include <stdio.h>
    #include <math.h>
    main ()
    {
        double i,a;
    
        for(i=0.0; i <= 4.0 ;i++)
        {
            a=pow(10,i);
            printf("%lf\t",a);
        }
    }
    

    And got the following output:

    1.000000    10.000000   100.000000  1000.000000 10000.000000    
    
    0 讨论(0)
  • 2020-11-22 12:53

    The function pow() returns a double. You're assigning it to variable a, of type int. Doing that doesn't "round off" the floating point value, it truncates it. So pow() is returning something like 99.99999... for 10^2, and then you're just throwing away the .9999... part. Better to say a = round(pow(10, i)).

    0 讨论(0)
  • 2020-11-22 13:04

    This is to do with floating point inaccuracy. Although you are passing in ints they are being implicitly converted to a floating point type since the pow function is only defined for floating point parameters.

    0 讨论(0)
  • 2020-11-22 13:06

    I can't even spell c, but I can tell you why.

    You have set a to be an int. pow() generates a floating point number, that in SOME cases may be just a hair less than 100 or 10000 (as we see here.)

    Then you stuff that into the integer, which TRUNCATES to an integer. So you lose that fractional part. Oops. If you really needed an integer result, round may be a better way to do that operation.

    Be careful even there, as for large enough powers, the error may actually be large enough to still cause a failure, giving you something you don't expect. Remember that floating point numbers only carry so much precision.

    0 讨论(0)
  • 2020-11-22 13:11

    No one spelt out how to actually do it correctly - instead of pow function, just have a variable that tracks the current power:

    int i, a, power;    
    
    for (i = 0, a = 1; i <= 4; i++, a *= 10) {    
        printf("%d\t",a);    
    }
    

    This continuing multiplication by ten is guaranteed to give you the correct answer, and quite OK (and much better than pow, even if it were giving the correct results) for tasks like converting decimal strings into integers.

    0 讨论(0)
提交回复
热议问题