计蒜客 挑战难题 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

解法1:
二分法

#include 
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   
#include   
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函数引发的血案

你可能感兴趣的:(编程练习)