Sarah Ahmed
Sarah Ahmed

Reputation: 5

What am I doing wrong with this modulus?

I wrote a C++ program that receives from user a number and print 1 if positive and even, Print 2 if positive and odd, Print 3 if negative and even, print 4 if negative and odd, print 0 if zero. Here's my code:

#include <iostream>
using namespace std;
int main () {
int n;
cin>>n;
if (n>0 && n%2==0)
    cout <<"1";
else if (n>0 && n%2==!0)
    cout <<"2";
else if (n<0 &&  n%2==0)
    cout <<"3";
else if (n<0 && n%2==!0)
    cout <<"4";
else if (n==0)
cout <<"0";
return 0;

}

Everything run pretty well except the 4th case whenever I enter negative and odd it prints nothing on the screen and that means nothing of all these cases are true, What am I doing wrong with the 4th, Isn't there a modulus to a negative number or what?

Upvotes: -2

Views: 80

Answers (1)

Bathsheba
Bathsheba

Reputation: 234715

Replace n%2==!0 with n % 2 != 0. The extra spacing is my personal taste.

n%2==!0 is evaluated as n%2==(!0) due to operator precedence, and !0 is equal to 1. Maddeningly, the way you have it works perfectly for the positive n case, but it breaks the negative n % 2 case which, for odd negative n, returns -1 from C++11 onwards. (Prior to that the result was implementation defined.)

Upvotes: 4

Related Questions