0

Just starting out with Python, so this is probably my mistake, but...

I'm trying out Python. I like to use it as a calculator, and I'm slowly working through some tutorials.

I ran into something weird today. I wanted to find out -1%4, and got this:

>>> -1%4
3

I checked it on c and c++ compiles as well, and 3 is the wrong answer! -1 % 4 is supposed to be 3.

Why is Python giving me a wrong answer?

Carcigenicate
  • 43,494
  • 9
  • 68
  • 117
  • 2
    I'm finding this confusing: ". . . and **3 is the wrong answer**! -1 % 4 is **supposed to be 3**." Can you clarify? Are you expecting -3? – Carcigenicate Feb 23 '19 at 17:44
  • 1
    "3 is the wrong answer, it is supposed to be 3", did you have a typo? Besides, there will be no "supposed to be" if you use negative during modulo. – Geno Chen Feb 23 '19 at 17:45
  • Possible duplicate of [What is the result of % in Python?](https://stackoverflow.com/questions/4432208/what-is-the-result-of-in-python) – raina77ow Feb 23 '19 at 17:48
  • In Modern C/C++, the result of `%`, if non-zero, always has the same sign as the first operand. In Python, the same sign as the second operand. Hence the difference. – raina77ow Feb 23 '19 at 17:50
  • @raina77ow I read [Modulo operation in Wikipedia](https://en.wikipedia.org/wiki/Modulo_operation) and it said the `%` in C is implementation defined... I don't know which one is right. Edit: Sorry, they are old standards. – Geno Chen Feb 23 '19 at 17:53
  • Also, there's no right or wrong here: as you [can see](https://en.wikipedia.org/wiki/Modulo_operation), various languages follow different conventions here. Some even have two different operators for 'sign by divisor' and 'sign by dividend'. – raina77ow Feb 23 '19 at 17:53
  • 1
    A finer duplicate is this one: https://stackoverflow.com/questions/1907565/c-and-python-different-behaviour-of-the-modulo-operation – raina77ow Feb 23 '19 at 17:56
  • ok.... does that means different programming language solves/give different results for same program?? I don't think so it must be the same for all...?! – Anshraj Shrivastava Mar 01 '19 at 19:26

0 Answers0