[SOLVED] Float value not displayed


(Pritesh Ugrankar) #1

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:

  1. Where am I going wrong ?
  2. 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

(Norbert Melzer) #2

You are doing integer division and then casting the result to float, but you actually want to cast both parts of the division to float and then divide those to get a floating point division


(Pritesh Ugrankar) #3

Hi NobbZ,
I was suspecting that i’ve done something eminently stupid, and I was right. Thanks for your patience :slight_smile:
So I just changed this:

avgOfSumOfElements = float32(sumOfElements) / len(sliceSumOfElements))

To this:

avgOfSumOfElements = float32(sumOfElements) / float32(len(sliceSumOfElements))

And it worked.