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

2019-03-01 06:40发布

Why does this:

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

returns 0? I expected it to return 1.

2条回答
乱世女痞
2楼-- · 2019-03-01 07:21

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.

查看更多
劳资没心,怎么记你
3楼-- · 2019-03-01 07:24

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)

查看更多
登录 后发表回答