0

When I tried -12//5 I expected -2 but it returned -3. why it is so?

ChrisGPT was on strike
  • 127,765
  • 105
  • 273
  • 257
  • 1
    Welcome to Stack Overflow. [Please don't post screenshots of text](https://meta.stackoverflow.com/a/285557/354577). They can't be searched or copied, or even consumed by users of adaptive technologies like screen readers. Instead, paste the code as text directly into your question. If you select it and click the `{}` button or Ctrl+K the code block will be indented by four spaces, which will cause it to be rendered as code. – ChrisGPT was on strike Dec 09 '22 at 16:54
  • 1
    Everyone has strong opinions on what the modulo of a negative number is, **especially** programming languages. Not everyone agrees. – tadman Dec 09 '22 at 16:55
  • 1
    This is not about mod but about flooring and flooring `-2.whatever` is **obviously** supposed to give `-3`. – luk2302 Dec 09 '22 at 16:55
  • @luk2302 Not entirely. The result of `//` and `%` are defined in tandem so that when `q, r == divmod(n, d)`, then `n * d + r == q` and `d` and `r` have the same sign. It's not the *only* possible definition for the operators involved, but asking why the language designers chose one definition over the other gets into opinion territory. – chepner Dec 09 '22 at 17:00
  • (Corrected my previous comment to emphasize that `//` was chosen to represent floored division, rather than some other possible version of integer division.) – chepner Dec 09 '22 at 17:03
  • @chepner if the `//` is called "floor division" it is obvious what it does but evidently if you do not know the name you can assume a different behaviour and then you are once again in the "opinion territory" why it *is* a floor division. (I agree) – luk2302 Dec 09 '22 at 17:05
  • Keep in mind that flooring is different than rounding .. So `-2.00001` will still floor as `-3` – Zak Dec 09 '22 at 17:25
  • Whereas `2.00001`or `2.9999` for that matter .. will floor as `2` – Zak Dec 09 '22 at 17:39

0 Answers0