Trouble with float on C [duplicate]

时光怂恿深爱的人放手 提交于 2019-11-26 11:44:19

问题


I have this little program in C that calculates the square root x of a positive integer N using a recursive function (implemented using a while loop). If I calculate x using this:

x = (1/2)*(x + N/x) //x0 = 1.0

Then x keeps growing to inf and then nan. However if I use this:

x = (x + N/x)/2 //x0 = 1.0

It works fine, why? Thanks.


回答1:


1/2 does integer division, its result is 0, change either or both operand to double, e.g:

1.0/2


来源:https://stackoverflow.com/questions/26643536/trouble-with-float-on-c

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