#include<iostream>
#include<algorithm>
using namespace std;
int main(){
double x;
cin >> x;
double l = 0, r = max(x, 1);
while(r - l > 1e-8){//保留五位小数1e-7,否则6位小数1e-8,经验值,比有效位数多2
double mid = (l + r) / 2;
if(mid * mid >= x) r = mid;
else l = mid;
}
printf("%lf", l);
return 0;
}
法二:不用精度,直接迭代一百次
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
double x;
scanf("%lf", &x);
double l = 0, r = max(x, 1);
for(int i = 0; i < 100; i ++ ){
double mid = (l + r) / 2;
if(mid * mid >= x)r = mid;
else l = mid;
}
printf("%lf", l);
return 0;
}