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,&&).
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))))
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)));
python===> True
c++=====> 1
python===> True
c++=====> 0
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))))
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.