题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
package main import ( "fmt" "math" ) func main() { var input float64 fmt.Scan(&input) if input == 0 || input == 1 || input == -1 { fmt.Printf("%.1f", input) return } var ne = input < 0 if ne { input = input * -1 } var small = input < 1 var low, mid, high, triple float64 if small { low = 0 high = 1 } else { low = 1 high = input } for { mid = (low+high) / 2 triple = mid*mid*mid if math.Abs(input - triple) < 0.01 { break } else if triple > input { high = mid } else if triple < input { low = mid } } if ne { mid *= -1 } fmt.Printf("%.1f", mid) }
// 本题输入一个浮点数,所以采用:fmt.Scan(&input)