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

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

Tour of Go Exercise #8: Loops and Functions

问题

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

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

出了什么问题?

  1. package main
  2. import (
  3. "fmt"
  4. "math"
  5. )
  6. func Sqrt(x float64) float64 {
  7. guess := 1.0
  8. i := 1
  9. for i < 10 {
  10. guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
  11. }
  12. return guess
  13. }
  14. func main() {
  15. fmt.Println(Sqrt(2))
  16. }
英文:

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 ?

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;math&quot;
  5. )
  6. func Sqrt(x float64) float64 {
  7. guess := 1.0
  8. i := 1
  9. for i &lt; 10 {
  10. guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
  11. }
  12. return guess
  13. }
  14. func main() {
  15. fmt.Println(Sqrt(2))
  16. }

答案1

得分: 6

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

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

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

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

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:

确定