Hi,
I was trying to write a function that would take in two slices, add the elements of each slice to a third slice, then return : the slice that has each elements of the two slices added, the sum of the elements in the third slice and the average.
I noticed that though the average is declared as a float, it was not showing a float value.
So I removed the function and did all the above calculations in the main function. I still get the same results.
I have two questions:
- Where am I going wrong ?
- If something is not working in a function, is writing it in the main loop and trying to troubleshoot a good way of finding issues? Of course this will not apply to every situation, but still, whenever possible, is doing this a good way to troubleshoot an issue?
Here’s the code:
package main
import "fmt"
func main() {
myFirstSlice := []int{1, 2, 3, 4, 5, 6}
mySecondSlice := []int{7, 8, 9, 10, 11, 15}
sliceSumOfElements := make([]int, len(myFirstSlice))
var sumOfElements int
var avgOfSumOfElements float32
for index, _ := range sliceSumOfElements {
sliceSumOfElements[index] = myFirstSlice[index] + mySecondSlice[index]
sumOfElements += sliceSumOfElements[index]
}
avgOfSumOfElements = float32(sumOfElements / len(sliceSumOfElements))
fmt.Println(sliceSumOfElements, sumOfElements, len(sliceSumOfElements), avgOfSumOfElements)
}
And here’s the output:
>go run main.go
[8 10 12 14 16 21] 81 6 13