dongqiuxu2270 2018-06-01 17:29
浏览 98

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

Below are two attempts to solve the exercise at https://tour.golang.org/flowcontrol/8. One version makes a function call as part of the for condition, but this doesn't work - it doesn't even execute the loop body. If I move the condition inside the loop itself, it works as I expected. Why?

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))
}

Output

1.4142156862745099
1
  • 写回答

1条回答 默认 最新

  • dongqiulei6805 2018-06-01 17:32
    关注

    Your if condition is signalling when the loop should stop, but the for condition signals when the loop should continue.

    To see the desired result, invert your for condition:

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

报告相同问题?

悬赏问题

  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加