code blocks power function is not working in c

前端 未结 5 868
陌清茗
陌清茗 2021-01-26 19:47

i am using code block for learning c. my code is

#include
#include
int main()
{
  int x;
  x = pow(5,2);
  printf(\"%d\", x);
}

Out         


        
5条回答
  •  情书的邮戳
    2021-01-26 20:39

    I suspect you have a naive implementation of pow in your libm (I get 25, as it should be). If that computes pow(x,y) as exp(y*log(x)) for positive x without checking for (small) integral exponents and treating them specially, you get

    Prelude> 2 * log 5
    3.2188758248682006
    Prelude> exp it
    24.999999999999996
    

    a double result slightly smaller than 25, so when that is converted to int it is truncated to 24.

    To check, assign the result of pow(i,j) to a double and print that out.

    With hardcoded pow(5,2), the compiler (most likely, it's what gcc does even without optimisation) computes the result during compilation exactly.

提交回复
热议问题