浮点数二分法

浮点数二分法

题意:求 (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 = '
';
//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;
}

原文地址:https://www.cnblogs.com/xiaoran991/p/14403136.html