js 用二分法实现开立方根

2024-02-21  本文已影响0人  泪滴在琴上

数字可以是负数可以是浮点数,输出的值最多保留1位小数

 let num =19.9;
        let low=0;
        let heigh=Math.abs(num);
        let mid = 0;
        while(heigh-low>0.0001){
            mid = (low+heigh)/2;
            if( mid*mid*mid>Math.abs(num)){
               heigh=mid 
            }else{
               low = mid;
            }
        }
        
        let result =num<0? -(low+heigh)/2:(low+heigh)/2
       console.log(result.toFixed(1))
上一篇下一篇

猜你喜欢

热点阅读