英文:
How to assign an int returned by a function to a variable?
问题
我刚开始学习Go语言,遇到了一个非常简单的问题。我通过解决一些简单的问题集来学习,目前我正在尝试打印小于1000万的斐波那契数列。我的斐波那契函数没问题,但我不知道如何将其值赋给一个变量,然后在控制结构中使用。例如:
package main
import "fmt"
func fib() func() int {
x, y := 0, 1
return func() int {
x, y = y, x+y
return x
}
}
func main() {
f := fib()
for f() <= 10000000 {
fmt.Println(f())
}
}
我知道我在这里漏掉了一些简单的东西,但是这个代码不应该一直调用我的函数并获取斐波那契数列中的下一个数字,直到该数字不大于或等于1000万吗?我收到一个错误,告诉我类型不匹配,func() (int和int)。我知道这很简单,我可能只是个白痴。提前谢谢你的帮助。
英文:
I am new to Go and having some issues with figuring out a really simple problem. I am learning by working through some simple problem sets and at the moment am trying to print the sequence of Fibonacci numbers that are smaller than 10 million. My Fibonacci function is fine but I am not sure how to assign its value to a variable which I can then use in control structures. For instance:
package main
import "fmt"
func fib() func() int {
x, y := 0, 1
return func() int {
x, y = y, x+y
return x
}
}
func main() {
f := fib()
for f <= 10000000 {
fmt.Println(f())
}
}
I know I am missing something simple here but should this not keep calling my function and grabbing the next number in the Fibonacci sequence until that number is no greater than or equal to 10 million? I receive an error telling me there are mismatched types func() (int and int). I know this is dead simple and I am likely just an idiot.
Thanks in advance.
答案1
得分: 1
尝试调用该函数:
for x := f(); x < 100; x = f() {
fmt.Println(x)
}
请注意,这是一段Go语言代码,用于循环调用函数f()
并打印结果,直到x
的值小于100。
英文:
Try calling the function:
for x := f(); x < 100; x = f() {
fmt.Println(x)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论