题解 | #求解立方根#
求解立方根
https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca
牛顿法:
要求 的解,记 ,牛顿法求根:
package main import ( "fmt" "math" ) func main(){ var n float64 fmt.Scanf("%f", &n) x0 := 3.0 x1 := 1.0 for math.Abs(x1-x0) > 1e-2{ x1, x0 = x0-(x0*x0*x0 - n)/(3*x0*x0), x1 } fmt.Printf("%.1f", x1) }
简单点:
package main import "fmt" import "math" func main(){ var num float64 fmt.Scanln(&num) precise := 1e-3 t := num for math.Abs(t*t*t - num) > precise{ t = t - (t*t*t - num)/(3*t*t) } fmt.Printf("%.1f", t) }