3 ms·
Hmmm, having a go with er... Go: fmt.Println(19 % 12) fmt.Println(19 % -12) ======= 7 7 Hmmm, let's try the built in math package then: fmt.Print
by justinclift 8y ago
Hmmm, having a go with er... Go:
fmt.Println(19 % 12)
fmt.Println(19 % -12)
=======
7
7
Hmmm, let's try the built in math package then:
fmt.Println(math.Mod(19, 12))
fmt.Println(math.Mod(19, -12))
=======
7
7
Looking at math.Mod()'s description:
// Mod returns the floating-point remainder of x/y.
// The magnitude of the result is less than y and its
// sign agrees with that of x.
k, that seems like it's not supposed to be "modulus" then.
The Go language spec(https://golang.org/ref/spec#Arithmetic_operators https://golang.org/ref/spec#Arithmetic_operators) also clearly states it's remainder not modulus.
% remainder integers
The manual approach does work:
m := 19
n := -12
fmt.Println(((m % n) + n) % n)
=======
-5
Doing a bit of searching online shows some discussion in 2009, but no mention of any desire for a change:
• https://github.com/golang/go/issues/448#issuecomment-66049769 https://github.com/golang/go/issues/448#issuecomment-6604976...
• https://github.com/golang/go/issues/448#issuecomment-66049770 https://github.com/golang/go/issues/448#issuecomment-6604977...
Does anyone know if this has improved since?