英文:
Go — declared and not used error, when I think I have done so to the variable
问题
这段代码有什么问题?
package main
import "fmt"
// fibonacci 是一个返回一个 int 的函数的函数。
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr := curr + prev
prev := temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
prog.go:13: prev 声明但未使用
英文:
What's wrong with this code?
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr := curr + prev
prev := temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
prog.go:13: prev declared and not used
答案1
得分: 16
你声明了一个名为prev
的变量,但是从未使用过。
具体来说,你写了prev := temp
。这在当前作用域中创建了一个名为prev
的新局部变量。我猜你的意思是只需要写prev = temp
,这样会修改继承自外部作用域的prev
变量。同样,你可能在上一行中想要写curr = curr + prev
,而不是使用:=
。
英文:
You declared a variable named prev
and then never used it.
Specifically, you said prev := temp
. This is creating a new local variable in the current scope named prev
. I assume you meant to just say prev = temp
, which modifies the prev
variable inherited from the surrounding scope. Similarly you probably meant to say curr = curr + prev
on the previous line, instead of using :=
.
答案2
得分: 3
如果你按照Kevin Ballard的建议进行更改,那么,
package main
import "fmt"
// fibonacci是一个返回
// 返回一个int的函数。
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr = curr + prev
prev = temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
输出:
1
2
3
5
8
13
21
34
55
89
输出不是Fibonacci数列。
对于Fibonacci数列,
package main
import "fmt"
func fibonacci() func() int {
a, b := 0, 1
return func() (f int) {
f, a, b = a, b, a+b
return
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
输出:
0
1
1
2
3
5
8
13
21
34
英文:
If you make the changes suggested by Kevin Ballard, then,
package main
import "fmt"
// fibonacci is a function that returns
// a function that returns an int.
func fibonacci() func() int {
prev := 0
curr := 1
return func() int {
temp := curr
curr = curr + prev
prev = temp
return curr
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Output:
1
2
3
5
8
13
21
34
55
89
The output is not the Fibonacci sequence.
For the Fibonacci sequence,
package main
import "fmt"
func fibonacci() func() int {
a, b := 0, 1
return func() (f int) {
f, a, b = a, b, a+b
return
}
}
func main() {
f := fibonacci()
for i := 0; i < 10; i++ {
fmt.Println(f())
}
}
Output:
0
1
1
2
3
5
8
13
21
34
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论