计蒜客第17题---X的平方根

设计函数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;
}



                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值