Go语言之旅练习 #8:循环和函数

huangapple go评论85阅读模式
英文:

Tour of Go Exercise #8: Loops and Functions

问题

我正在尝试解决Go Tour的练习#8

我的解决方案出现了一个错误信息the process to take too long

出了什么问题?

package main

import (
    "fmt"
    "math"
)

func Sqrt(x float64) float64 {
    guess := 1.0
    i := 1
    for i < 10 {
        guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
    }
    return guess
}

func main() {
    fmt.Println(Sqrt(2))
}
英文:

I am trying to solve the exercise #8 of the Go Tour.

My solution fails with an error message the process to take too long

What is wrong ?

package main

import (
    &quot;fmt&quot;
    &quot;math&quot;
)

func Sqrt(x float64) float64 {
    guess := 1.0
    i := 1
    for i &lt; 10 {
        guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
    }
    return guess
}

func main() {
    fmt.Println(Sqrt(2))
}

答案1

得分: 6

你在循环中没有增加i变量的值,所以它始终小于10。

 //-----------v
for ; i < 10; i++ {
    guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
}
英文:

You're not incrementing the i variable in your loop, so it's always &lt; 10.

 //-----------v
for ; i &lt; 10; i++ {
    guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
}

huangapple
  • 本文由 发表于 2013年3月15日 09:34:43
  • 转载请务必保留本文链接:https://go.coder-hub.com/15423241.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定