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

三世轮回 提交于 2019-12-31 04:42:06

问题


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.



来源:https://stackoverflow.com/questions/30669654/pow1-0-returns-0

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!