Weird println in golang


(Pamleft) #1
n := 43210 // time in seconds
fmt.Println(n/60*60, "hours and", n%60*60, "seconds")

result:

43200 hours and 600 seconds

I don’t know why.


(catacombs) #2

What are you trying to do?

To get the hours, I changed your math a bit:

fmt.Println((n / 60) / 60, "hours")


(Johan Dahl) #3

Or you could write it like this

n / (60*60)


(Pamleft) #4

In other language, such as Java and C, the print output is the result of n/60*60(it’s 12). So I don’t know why the golang is so different. Is that the bug of the golang?


(Norbert Melzer) #5

Division and multiplication do have the same precedence in go, so they are evaluated left to right.

And I can not check for C right now, but the behaviour for Elixir, Erlang and Rust is the same as Gos, all read and evaluate it like if it were (n / 60) * 60.


(Zhong Qin) #6

Definitely not.
And for Java and C, they work as the same as Go.


(Pamleft) #7

It’s very shameful, I got it wrong.