問題內(nèi)容
我是編程和 stackoverflow 的初學(xué)者。
我必須在 go 中創(chuàng)建一個遞歸函數(shù)來添加數(shù)組的元素,如果數(shù)組的長度為 0,則返回 0。
func Suma(vector []int) int {
n := len(vector)
if n == 0 {
return 0
} else {
return Suma(vector[n] + vector[n-1])
}
}
func main() {
fmt.Println("Hello, 世界")
vector := []int{1, 2, 3, 4, 5}
res := Suma(vector)
fmt.Println(res)
}
登錄后復(fù)制
它給了我這個錯誤,但我不明白。
cannot use vector[n] + vector[n - 1] (value of type int) as []int value in argument to Suma
登錄后復(fù)制
為什么會出現(xiàn)此錯誤以及如何修復(fù)它?
正確答案
這是你的問題:
您看到的錯誤消息是因為您嘗試將 int 值傳遞給 Suma 函數(shù),該函數(shù)需要一個 int 切片。
package main
import "fmt"
func Suma(vector []int) int {
n := len(vector)
if n == 0 {
return 0
} else {
// You should call Suma recursively with a slice of the vector, excluding the last element.
// Also, you need to add the current element (vector[n-1]) to the sum.
return vector[n-1] + Suma(vector[:n-1])
}
}
func main() {
fmt.Println("Hello, 世界")
vector := []int{1, 2, 3, 4, 5}
res := Suma(vector)
fmt.Println(res)
}
登錄后復(fù)制






