Blank output when entering negative numbers

Hi we've been given the task to create a program to find out if the number that has been inputted by the user is an even or odd number and if its also a positive or negative number or a zero. Down below is the code that i made but im having trouble since the program won't put the expected output when entering a negative number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <iostream>
using namespace std;
int main(){
	
	int num;
	cin >> num;
	
	if (num % 2 == 0 && num > 0){
		cout << "\nThe number " << num << " is EVEN and its a POSITIVE number.";
	}else if (num % 2 == 0 && num < 0){
		cout << "\nThe number " << num << " is EVEN and its a NEGATIVE number.";
	}else if (num % 2 == 1 && num > 0){
		cout << "\nThe number " << num << " is ODD and its a POSITVE number.";
	}else if (num % 2 == 1 && num < 0){
		cout << "\nThe number " << num << " is ODD and its a NEGATIVE number.";
	}else if(num == 0){
		cout << "\nThe number " << num << " is EVEN and its a ZERO.";
	}
	
	return 0;
}
Last edited on
% (modulus operator) is weird on negative numbers. It isn't quite the same as the mathematical concept of (n mod m).

(-1 % 2) == -1, not 1.
So change your condition from (n % 2 == 1) to (n % 2 != 0).
Thanks! much appreciate it!
Hello shunin,

When all fails use a calculator that you are sure of and as Ganado pointed out on my Windows calculator -9 % 2 evaluates to -1.

I fine it useful when you have many if/else if statements to work with.

Andy
another way to look... if the most significant bit is set, its negative, and if the least bit is set, its odd.
that just leaves zero as the edge case.
so for a byte, 8 bits, any byte & 1000 0001 cast to unsigned for logic ops will give you one of 0, 1, 128, 129. 0 means its either 0 or even and positive, 1 means its odd and positive, 128 is even and negative, 129 is odd and negative. the idea is the same but the values change for bigger bitsized ints.
circle back to this if you have not done bitwise logic yet. For now its just an interesting side-track. Later, if and when you need speed, its a faster side-track: logic operations cost less than math ones in general, and modulo specifically isnt cheap.
Last edited on
Correction: Modulo is implementation-specified for negative operands. But it's true that on most implementations it follows truncated division, which gives (-divisor; 0] for negative dividends and positive divisors.
You can turn any modulo into Euclidean modulo like this:
1
2
3
4
5
6
int euclidean_modulo(int dividend, int divisor){
    assert(divisor > 0);
    if (dividend < 0)
        return divisor - -dividend % divisor;
    return dividend % divisor;
}
Topic archived. No new replies allowed.