Search code examples
cpow

Why the pow function when used in printf() produce arbitrary results?


I have this code in C-

#include <stdio.h>
#include <math.h>
int main()
{
    printf("%d",(12345/pow(10,3)));
}

It outputs any arbitrary value,why is it not outputting 12? Isn't the above code equivalent to-

#include <stdio.h>
#include <math.h>
int main()
{
    int i=12345/pow(10,3);
    printf("%d",i);
}

It outputs 12, Why the two codes outputting different values?Can someone please explain.


Solution

  • pow returns a double, therefore causing undefined behavior because you pass it to a format string expecting an int, since typeof(int / double) == double.

    Try

    printf("%lf\n", 12345 / pow(10, 3));
    

    or use an explicit cast, like

    printf("%d\n", 12345 / (int) pow(10, 3));