浮点数二分法

浮点数二分法

题意:求 \(\sqrt{x}\)

#include <bits/stdc++.h>
using namespace std;

// 保留4位小数 -> 1e-6
// 保留5位小数 -> 1e-7
// 保留6位小数 -> 1e-8
const double eps = 1e-8;
const char nl = '\n';
//const int N = ;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cout << fixed << setprecision(6);

    double x;
    cin >> x;

    double l = 0, r = x;
    while (r - l > eps){
        int Mid = (l + r) / 2;
        if (Mid * Mid > r) r = Mid;
        else l = Mid;
    }

    cout << r << nl;
    return 0;
}

posted @ 2021-02-15 01:26  小燃、  阅读(47)  评论(0编辑  收藏  举报