go官网Exercise题目以及我的答案
1.Exercise: Loops and Functions
该题目出现的时候教程中并未介绍取绝对值的函数,所以这里也是按照不知道该函数的思路写的答案,可能与普通情况略有不同。
package main import ( "fmt" ) func Sqrt(x float64) float64 { z := x / 2 var item float64 = x for i := 0; item > 1e-16; i++ { lastResult := z z -= (z*z - x) / (2 * z) if z-lastResult < 0 { item = lastResult - z } else { item = z - lastResult } fmt.Println("Current result of the sqrt is", z) } return z } func main() { fmt.Println(Sqrt(16)) }