题解 | #求解立方根#
求解立方根
http://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
package main
import (
"fmt"
"math"
)
func main() {
var (
input float64
)
fmt.Scan(&input)
if input == 0 || input == 1 {
fmt.Println(input)
return
}
var (
l float64
r float64
flag = 1.0
)
//负数的情况
if input < 0 {
flag = -1.0
}
input = math.Abs(float64(input))
//考虑小于1的情况
if input > 1 {
l = 0
r = input
} else {
l = input
r = 1
}
//二分查找
mid := l + (r-l)/2
for math.Abs(mid*mid*mid-input) > 0.001 {
if mid*mid*mid > input {
r = mid
} else {
l = mid
}
mid = l + (r-l)/2
}
fmt.Printf("%0.1f", mid*flag)
}