package main import ( "fmt" ) type ErrNegativeSqrt float64// 实现Error接口,ErrNegativeSqrt 可以作为一个error来用 func (e ErrNegativeSqrt) Error() string { return fmt.Sprintf("cannot Sqrt negative number: %v", float64(e)) } func Sqrt(x float64) (float64, error) { if x < 0 { return 0, ErrNegativeSqrt(x) } z := x/2 var t float64 for { t = z z = z - (z*z - x)/(2*x) if t - z > -0.001 && t - z < 0.001 { break } } return z, nil } func main() { fmt.Println(Sqrt(2)) fmt.Println(Sqrt(-2)) }
时间: 2024-10-16 19:12:48