Search code examples
cpow

How to use pow() function in the printf() statement itself?


I am trying to use pow() function in my code to print 3 raised to the power of 2.

I used pow function in the printf() statement itself like this.

printf("%d",pow(3,2));

Output:

0

However When I tried to first assign it to a variable and then print it, It functioned perfectly.

int c;
c=pow(3,2);
printf("%d",c);

Output:

9

I have also tried to use a dummy function returning integer in the printf() statement directly and that too worked fine.

If so, what is the problem in first statement?


Solution

  • The problem is the format specifier. pow returns a double, whereas %d specifies an int.

    Given the number of architectures out there and how very clear the demarcation between 'integral' and 'floating point' is on most platforms, in general, you cannot treat the result of a function returning double as an int in a format string and expect the correct output.

    The reason it works when you assign the result of pow to c (which I assume is an int since it works with %d) is because in that case your compiler knows to implicitly cast the result, but doesn't when the only indication of the type of a variable is in a format string.

    Solution: either change %d to %f or explicitly cast the result of pow to int.