英文:
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 (
"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))
}
答案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 < 10
.
//-----------v
for ; i < 10; i++ {
guess = guess - (math.Pow(guess, 2)-x)/(2*guess)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论