Search code examples
cpow

Why does pow output 0 even when using %f?


I am completely new to c, so I was trying to use the pow function as I'm following a tutorial. On the tutorial (and I followed the code exactly as they wrote it), their output is correct, but all I get is 0.000000. Does anyone know why this happened?

#include <stdio.h>
#include <stdlib.h>

int main() {

    printf("%f", pow(4, 3));



    return 0;
}

Output

0.000000

Solution

  • Insert #include <math.h>, turn on warnings in your compiler, pay attention to warning messages, and promote warnings to errors.

    Without <math.h>, pow is not declared, and pow(4, 3) passes arguments as int. pow needs its arguments passed as double, the behavior when they are passed as int is not defined by the C standard. Further, the return type of pow will be assumed to be int, but the actual return type is double, and the behavior of the function call with this mismatch is also not defined. And passing an int value for a printf conversion of %f also has behavior not defined by the C standard.