设计函数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
<pre name="code" class="cpp">#include <iostream>
#include <cmath>
using namespace std;
//也可以执行,但是会超时
/*int sqrt(int x)
{
if(x==1)
return 1;
for(int i=1;i<=x/2;i++)
{
if(i*i>x)
return i-1;
}
}
*/
/*int sqrt(int x)
{
int sum_n = 1;
int n = 1;
if(x <= 1)
{
return x;
}
while(sum_n <= x)
{
n++;
sum_n += (n<<1) - 1;
}
return (n-1);
}
*/
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 n,m;
while(cin >>n)
cout<<sqrt(n) <<endl;
return 0;
}