pow(1,0) returns 0? [closed]

2019-03-01 06:41发布

问题:

Why does this:

printf("%d\n", pow(1,0)); /* outputs 0 */

returns 0? I expected it to return 1.

回答1:

pow() returns a double type. You need to use %f format specifier to print a double.

Using inappropriate format specifier for the supplied argument type causes undefined behaviour. Check chapter §7.21.6.1 of the C standard N1570 (C11). (Yes, this has nothing specific to C89, IMHO)



回答2:

You need to type cast the result to int as pow() returns double.

printf("%d\n",(int) pow(1,0));

This give your desired output 1

note:pow(a,b) gives correct result when both a and b are integers as in your case.But you need to add 0.5 to the result when dealing with fractions so that the result gets rounded off to nearest integer.

printf("%d\n",(int) (pow(2.1,0.9)))// will return 1. 

printf("%d\n",(int) (pow(2.1,0.9)+0.5));//will return 2.

Hope it helps you.