您的位置:首页 > 其它

计蒜客 挑战难题 X的平方根

2016-04-17 21:30 363 查看
题目:

设计函数int sqrt(int x),计算x的平方根。

格式:

输入一个数x,输出它的平方根。直到碰到结束符号为止。

千万注意:是int类型哦~

输入可以如下操作:

while(cin>>x)

或者

while(scanf(“%d”, &x) != EOF)

样例1

输入:

1
2
3
4
5
6
7
8
9


输出:

1
1
1
2
2
2
2
2
3


解法1:

二分法

#include <stdio.h>
int nsqrt(int x)
{
double l=0,h,m=1.0,eps;
h = x;
eps = x - m*m;
while(eps > 0.001)
{
m = (l+h)/2.0;
if(m*m > x)
{
h = m;
eps = m*m - x;
}
else
{
l = m;
eps = x - m*m;
}

}
return m;
}

int main(int argc, char *argv[])
{
int x;
while(scanf("%d",&x) != EOF)
printf("%d\n",nsqrt(x));

return 0;
}


解法2:

牛顿法

#include <iostream>
#include <cmath>
using namespace std ;

int sqrt(int x)
{
double t=1.0;
while(abs(t*t-x)>1e-5)
{
t=(x/t+t)/2.0;
}
return t;
}
int main()
{
int x ;
while(cin>>x)
{
cout << sqrt(x) << endl ;
}
}


参考:

一个Sqrt函数引发的血案
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  二分法