Implement int
sqrt(int x).
Compute and return the square root of x.
牛顿迭代
class Solution {
public:
int sqrt(int x) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(x==0) return 0;
double value = x;
double last = value;
double next = value;
do
{
last = next;
next = (last+value/last)/2.0;
}while(abs(next-last)>0.000001);
return next;
}
};
本文介绍了一种使用牛顿迭代法实现计算整数平方根的C++代码示例。该方法通过迭代逐步逼近目标值,直至达到所需精度。
299

被折叠的 条评论
为什么被折叠?



