Strange behaviour of the pow function

后端 未结 5 707
借酒劲吻你
借酒劲吻你 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 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.

提交回复
热议问题