在 C 上浮动的问题 [英] Trouble with float on C
本文介绍了在 C 上浮动的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 C 语言小程序,它使用递归函数(使用 while 循环实现)计算正整数 N
的平方根 x
.如果我计算 x
使用这个:
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
然后 x
不断增长到 inf 然后是 nan.但是,如果我使用这个:
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/2
做整数除法,结果为0
,将其中一个或两个操作数改为double
,例如:
1/2
does integer division, its result is 0
, change either or both operand to double
, e.g:
1.0/2
这篇关于在 C 上浮动的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文