-1

I made a prototype code on python to see if the logic works and later coded it in c++. But for some reason the python version and c++ version return different results. I am not able to figure out why that is the case.

I went through this particular logical equation many times and made sure they are exactly the same, excluding differences like (or,||) and (and,&&).

python

i = -6
j = -5
pos_i = 0
pos_j = 0
print((i%2==0)and((((i/2)%2==0)and(j%2==0))or(((i/2)%2==1)and(j%2==1))))

c++

int i = -6;
int j = -5;
int pos_i = 0;
int pos_j = 0;
cout << (i%2==0)&&((((i/2)%2==0)&&(j%2==0))||(((i/2)%2==1)&&(j%2==1)));

expected:-

python===> True

c++=====> 1

actual:-

python===> True

c++=====> 0

sparkles
  • 174
  • 8

2 Answers2

2

Because in c++ i / 2 becomes an integer, whereas in python it becomes a float. From there you are doing logic with different values. If you wanted the same you should use

    print((i%2==0)and((((i//2)%2==0)and(j%2==0))or(((i//2)%2==1)and(j%2==1))))
ChrisMM
  • 8,448
  • 13
  • 29
  • 48
dangee1705
  • 3,445
  • 1
  • 21
  • 40
  • You would be correct for different values of i and j, but this is not the reason the C++ version is giving an unexpected result. -1 % 2 returns as -1 in C++ but 1 in python. – pigi5 Oct 28 '19 at 18:39
0

The other answer about integer division is correct, but that is not the problem here. The only division happening here is -6 divided by 2, so using the integer division operator // will not change the result.

The correct answer is that the modulo operator works differently in Python and C++: Link.

Unlike C or C++, Python's modulo operator (%) always return a number having the same sign as the denominator (divisor).

-1 % 2 in C++ will yield -1, instead of 1 like you are expecting.

pigi5
  • 74
  • 1
  • 10