實數的三次方根

_l_x_y發表於2024-10-22

給定一個浮點數n,求它的三次方根.

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

int main(){
    double n , m , l , r;
    bool tar = false;
    cin >> n;
    if(n < 0) {
        n = -n;
        tar = true;
    }
    m = n / 2;
    if(abs(m) < 1){
        l = n;
        r = 1;
    }
    else{
        l = 0;
        r = n;
    }

    while(abs(pow(m , 3) - n) > 1e-9){
        if(pow(m , 3) > n){
            r = m;
        }
        else{
            l = m;
        }
        m = (l + r) / 2;
    }
    if(tar) printf("%.6f" , -m);
    else printf("%.6f" , m);
    
    return 0;
}

相關文章