I'm trying to create random grades and adding them to a test_scores
array. Then calculate the average.
This program:
package main
import (
"fmt"
"math/rand"
)
func main() {
i := 0
var test_scores [5]float64
for i < len(test_scores) {
test_scores[i] = rand.Float64()
i++
}
fmt.Println(test_scores)
var total float64 = 0
i = 0
for i < len(test_scores) {
total += test_scores[i]
i++
}
fmt.Println(total)
fmt.Println(total / len(test_scores))
}
produces:
main.go:24: invalid operation: total / 5 (mismatched types float64 and int)
This one works fine:
package main
import (
"fmt"
"math/rand"
)
func main() {
i := 0
var test_scores [5]float64
for i < len(test_scores) {
test_scores[i] = rand.Float64()
i++
}
fmt.Println(test_scores)
var total float64 = 0
i = 0
for i < len(test_scores) {
total += test_scores[i]
i++
}
fmt.Println(total)
fmt.Println(total / 5)
}
The only difference being that in the final line, I'm using a fixed 5
and on the non-working one, I'm using the len(test_scores)
call.
Len returns an integer as well, so what's up?