C's pow function refuses to work with variable exponent

后端 未结 5 1473
遥遥无期
遥遥无期 2021-01-17 20:59

Let\'s say I have the following code snippet:

int i; double value;
for(i = 0; i < CONSTANT; i++) {
  value = (double)pow(2, i);
}

Trying

相关标签:
5条回答
  • 2021-01-17 21:25

    It's a very interesting behavior, and a good learning example.

    To solve your problem, add

    -lm
    

    to your gcc command line (provided you're using gcc). This tells the compiler to link against the math library.

    What seems to be going on, is that if you're using

    pow(2.0, 3);
    

    the compiler realizes this expression evaluates to a constant, and does mere substitution.

    Thus, no library function has to be called.

    0 讨论(0)
  • 2021-01-17 21:26

    You need to link with -lm to actually include the math library.

    It worked for a hardcoded value because the compiler optimized the pow call away.

    0 讨论(0)
  • 2021-01-17 21:27

    The code for pow is part of the math library. You need to link in that library (in addition to the C library that is linked in by default).

    To do that, with gcc, specify -lm on the compiler invocation

    gcc ... -lm
    
    0 讨论(0)
  • 2021-01-17 21:28

    http://www.cplusplus.com/reference/clibrary/cmath/pow/

    In C, only the version taking two double parameters exists with this name. The other overloads are only available in C++.

    It looks like you can't pass an int, so just make i a double and that should work.

    0 讨论(0)
  • 2021-01-17 21:46

    You must link against the math library:

    gcc program.c -lm
    

    The reason is that GCC (and some other compilers) have a built-in pow() function for literal constants. So if you call pow() with 2.0 manually, the compiler will actually figure-out what the answer is and substitute that for you. With a variable input, the compiler must rely on the math library, which you must link against.

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