只有脚踩上去才知其远近和曲折

二分法开根号

#include <iostream>
#include <cmath>
#include <cstdio>
using namespace std;

#define EPS 1e-5
double mysqrt(double x) {
    double l = 0.0, r = x, mid;
    while (l < r) {
        mid = (l + r) / 2;
        if (fabs(mid * mid - x) < EPS) return mid;
        if (mid * mid > x) r = mid;
        else l = mid;
    }
    return r;
}

int main() {
    double x;
    while (cin >> x) {
        printf("%.4f\n", mysqrt(x));
        printf("%.4f\n", sqrt(x));
    }
    return 0;
}
点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注