Go gotcha: Why is my computation wrong?

Why doesn't this code compute the number of hours and seconds?

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

The *, /, and % operators have the same precedence and are evaluated left to right: n/60*60 is the same as (n/60)*60.

Insert a pair of parantheses to force the correct evaluation order:

fmt.Println(n/(60*60), "hours and", n%(60*60), "seconds")
12 hours and 10 seconds

Or better yet, use a constant:

const SecPerHour = 60 * 60
fmt.Println(n/SecPerHour, "hours and", n%SecPerHour, "seconds")
12 hours and 10 seconds

See Operator precedence for a complete explanation of the order of operations in Go expressions.


Be the first to comment!