将函数作为for循环条件的一部分调用是否可以?

jrb*_*jrb 2 go

以下是https://tour.golang.org/flowcontrol/8解决此练习的两次尝试.一个版本将函数调用作为for条件的一部分,但这不起作用 - 它甚至不执行循环体.如果我在循环内移动条件,它就像我预期的那样工作.为什么?

package main

import (
    "fmt"
    "math"
)

func Sqrt_working(x float64) float64 {
    var z float64 = 1.0

    for {
        if math.Abs((z*z) - x) < 0.0001 {
            break
        }
        z -= ((z*z - x) / (2*z))
    }

    return z
}

func Sqrt_not_working(x float64) float64 {
    var z float64 = 1.0

    for math.Abs((z*z) - x) < 0.0001 {
        z -= ((z*z - x) / (2*z))
    }

    return z
}

func main() {
    fmt.Println(Sqrt_working(2))
    fmt.Println(Sqrt_not_working(2))
}
Run Code Online (Sandbox Code Playgroud)

产量

1.4142156862745099
1
Run Code Online (Sandbox Code Playgroud)

Tim*_*per 5

if当循环应该停止时,您的条件是发出信号,但是for当循环应该继续时,条件发出信号.

要查看所需结果,请反转您的for条件:

for math.Abs((z*z) - x) >= 0.0001 {
    z -= ((z*z - x) / (2*z))
}
Run Code Online (Sandbox Code Playgroud)