我正在通过巡回赛 - 练习:错误.当我向平方根函数添加错误处理时,它握着我的手.
这是我的解决方案:
package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
fmt.Sprint(float64(e))
return fmt.Sprintf("cannot Sqrt negative number: %g", float64(e))
}
func Sqrt(x float64) (float64, error) {
z := 1.0
margin := 0.00000000000001
for {
if x < 0 {
return 0, ErrNegativeSqrt(x)
}
previousZ := z
z = z - (z*z-x)/(2*z)
if math.Abs(previousZ-z) < margin {
fmt.Println(previousZ, "-", z, "=", previousZ-z)
break
}
}
fmt.Println("math.Sqrt:", math.Sqrt(x))
return z, nil …Run Code Online (Sandbox Code Playgroud) 我的印象是,尽管语法有所不同,但下面的函数a和b在逻辑上是等效的。但是,它们不是,我也不了解它们之间的区别。
在我看来,他们俩都在分配:
任何人都可以帮助消除我对多变量分配以及函数a和函数b之间的逻辑差异的误解吗?
package main
import "fmt"
func a() (int, int, int) {
x:=1
y:=2
z:=3
z = x
x = y
y = x+y
return x, y, z
}
func b() (int, int, int) {
x:=1
y:=2
z:=3
z, x, y = x, y, x+y
return x, y, z
}
func main() {
fmt.Println(a()) // prints 2 4 1
fmt.Println(b()) // prints 2 3 1
}
Run Code Online (Sandbox Code Playgroud)