jeudi 20 juillet 2017

Finding if a signed and an unsigned integer are are both even or both odd c++

I have a int m and an unsigned int j that I want to determine if they are both even or both odd.

In the past I've been using

if((int(j)+m)%2)

to catch the case that only one is odd. But I'm concerned about the casting to int incorrectly changing the odd-even-ness of j.

Do either of these run into problems?

if(!(j%2)!=!(m%2))
if(bool(j%2)!=bool(j%2))

I know that

if(j%2!=m%2)

doesn't work because 'm%2' will produce -1 when m is negative, which will always evaluate to true no matter what the value of j%2.

Aucun commentaire:

Enregistrer un commentaire