Get your priorities right

yourbasic.org/golang

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

Answer

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 Operators: complete list for a full explanation of the evalutation order of operations in Go expressions.

Share this page: