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.
#include <iostream>
usingnamespace std;
int main(){
int num;
cin >> num;
if (num % 2 == 0 && num > 0){
cout << "\nThe number " << num << " is EVEN and its a POSITIVE number.";
}elseif (num % 2 == 0 && num < 0){
cout << "\nThe number " << num << " is EVEN and its a NEGATIVE number.";
}elseif (num % 2 == 1 && num > 0){
cout << "\nThe number " << num << " is ODD and its a POSITVE number.";
}elseif (num % 2 == 1 && num < 0){
cout << "\nThe number " << num << " is ODD and its a NEGATIVE number.";
}elseif(num == 0){
cout << "\nThe number " << num << " is EVEN and its a ZERO.";
}
return 0;
}
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.
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;
}