如何将函数返回的整数赋值给变量?

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

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 &quot;fmt&quot;

func fib() func() int {
    x, y := 0, 1
    return func() int {
	    x, y = y, x+y
	    return x
    }
}

func main() {
    f := fib()
    for f &lt;= 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 &lt; 100; x = f() {
	fmt.Println(x)
}

huangapple
  • 本文由 发表于 2016年5月25日 18:20:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/37434201.html
匿名

发表评论

匿名网友

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

确定