I want to do a simple thing:
func (this *ScoreProvider) getScore()(res float64) {
var score1 int16 = 500
var score2 int16 = 400
var score3 int16 = 300
var score4 int16 = 200
res = score1 * 0.25 + score2 * 0.25 + score3 * 0.25 + score4 * 0.25
return
}
But this reports an error:
can not use score1 * 0 + score2 * 0 + score3 * 0 + score4 * 0 (type int16) as type float64 in assignment
How can I do this right?
Your constants (0.25) are being truncated to intergers (0).
Two ways to solve:
cast the score1 etc variables to float32:
var score1 int16 = 500
var score2 int16 = 400
var score3 int16 = 300
var score4 int16 = 200
res := float32(score1)*0.25 + float32(score2)*0.25 + float32(score3)*0.25 + float32(score4)*0.25
fmt.Println("Score", res)
or more sensible, instead of declaring them as int16 declare them as float32 to begin with:
var score1a float32 = 500
var score2a float32 = 400
var score3a float32 = 300
var score4a float32 = 200
res2 := score1a * 0.25 + score2a * 0.25 + score3a * 0.25 + score4a * 0.25
fmt.Println("Result 1", res)
fmt.Println("Result 2", res2)
On the Go Playground
There's no automatic type promotion in go and you need to include explicit conversions instead.
I'd write your code something like this:
package main
import "fmt"
func getScore() float64 {
s1, s2, s3, s4 := int16(500), int16(400), int16(300), int16(200)
return (float64(s1) + float64(s2) + float64(s3) + float64(s4)) * 0.25
}
func main() {
fmt.Println(getScore())
}
Go does not provide implicit numeric conversion, see this FAQ: Why does Go not provide implicit numeric conversion?.
This means you can't mix different types when doing arithmetic operations. They have to be of the same type. Spec:
The operand types must be identical unless the operation involves shifts or untyped constants.
Your case is a little different because 0.25
is an untyped constant but since it has a fraction part it can't be converted/interpreted as int16
so you get a compile time error. From the spec:
It is an error if the constant value cannot be represented as a value of the respective type.
You have 3 options in this case:
Explicitly convert scores to float64
:
res = float64(score1) * 0.25 + float64(score2) * 0.25 +
float64(score3) * 0.25 + float64(score4) * 0.25
Use float64
type for your score
variables.
var score1 float64 = 500
var score2 float64 = 400
// ...
Since your algorithm calculates average, you can simply do:
res = float64(score1 + score2 + score3 + score4) / 4