英文:
undefined <type float32 has no field or method sum> error.How do I fix it?
问题
这是我的程序。当我运行它时,它会出现以下错误 - a.sum未定义(float32类型没有sum字段或方法)
package main
import (
"fmt"
)
type Calculation interface {
operation(input []float32)
}
type Addition struct {
sum float32
}
func (a Addition) operation(input []float32) {
a.sum = input[0]
for _, a := range input[1:] {
a.sum += a
}
fmt.Println("Sum :", a.sum)
}
func main() {
var n int
fmt.Println("Enter the no of inputs : ")
fmt.Scanln(&n)
var input []float32
input = make([]float32 , n)
fmt.Println("Enter the numbers ")
for i:=0 ; i <n ; i++ {
fmt.Scanln(&input[i])
}
var c Calculation
i := Addition{0}
c = i
c.operation(input)
}
我还编写了三个函数Subtraction、Multiplication和Division,与Addition函数的格式类似,但这三个函数都可以正常运行,只有Addition函数出现了这个错误。我无法弄清楚为什么会这样。
英文:
this is my program.When I run it, it gives the following error - a.sum undefined (type float32 has no field or method sum)
package main
import (
"fmt"
)
type Calculation interface {
operation(input []float32)
}
type Addition struct {
sum float32
}
func (a Addition) operation(input []float32) {
a.sum = input[0]
for _, a := range input[1:] {
a.sum += a
}
fmt.Println("Sum :", a.sum)
}
func main() {
var n int
fmt.Println("Enter the no of inputs : ")
fmt.Scanln(&n)
var input []float32
input = make([]float32 , n)
fmt.Println("Enter the numbers ")
for i:=0 ; i <n ; i++ {
fmt.Scanln(&input[i])
}
var c Calculation
i := Addition{0}
c = i
c.operation(input)
}
I have written 3 more functions Subtraction , Multiplication and Division with Addition. All of them follow similar format but those three run with out any error, Only addition is giving this error. Unable to figure out why.
答案1
得分: 1
你的循环中的变量a
与表示加法的变量a
重名了。将你的循环改为以下形式可以解决这个问题:
for _, v := range input[1:] {
a.sum += v
}
英文:
Your variable a
in the loop shadows the variable a
representing Addition. Changing your loop to this will solve the problem:
for _, v := range input[1:] {
a.sum += v
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论