设计函数int sqrt(int x)
,计算 x 的平方根。
输入格式
输入一个 整数 x,输出它的平方根。直到碰到文件结束符(EOF
)为止。
输出格式
对于每组输入,输出一行一个整数,表示输入整数的平方根。
样例输入
1 2 3 4 5 6 7 8 9
样例输出
1 1 1 2 2 2 2 2 3#include<cstdio> #include<iostream> #include<cmath> using namespace std; int sqrt(int x) { double l=0.0; double r=x; double mid; while(l<=r) { if(x==1) return 1; mid=(l+r)/2; if(fabs(mid*mid-x)<0.01) { int a; return a=(int)mid; } else if(mid*mid>x) { r=mid; } else if(mid*mid<x) { l=mid; } } } int main() { int n; while(cin>>n) { cout<<sqrt(n)<<endl; } }