undefined <type float32 has no field or method sum> error.How do I fix it?

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

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

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(&quot;Sum :&quot;, a.sum)
}
func main() {
  var n int
    fmt.Println(&quot;Enter the no of inputs  : &quot;)
    fmt.Scanln(&amp;n)    
    var input []float32
    input = make([]float32 , n)
    fmt.Println(&quot;Enter the numbers &quot;)
    for i:=0 ; i &lt;n ; i++ {
    fmt.Scanln(&amp;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      
}

huangapple
  • 本文由 发表于 2017年1月27日 15:33:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/41888915.html
匿名

发表评论

匿名网友

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

确定