-
code to test odd/even
This should be real easy but I'm not getting it.
User is prompted for an integer. I test the integer for being equal to zero or int % 1 !=0. Below I test against mod 2 for even/odd.
First it thinks everything is an odd integer. Second it thinks everything is odd. I thought % just gives you the remainder of the one figure divided by the other. Am I missing something?
Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int num = 0;
bool isOdd;
cout << "Enter an integer (whole number) and I will tell you" << endl;
cout << "if the number is odd or even: " << endl;
cin >> num;
if(num=0 || num % 1 != 0)
{
cout << "Not an integer. Shutting down." << endl;
}
if(num%2!=0)
{
isOdd = true;
}
if(isOdd=true)
{
cout << "Number is Odd." << endl;
}
if(isOdd=false)
{
cout << "Number is even." << endl;
}
system ("pause");
}
fyi: the only reason for the bool is because I tried the test with just the % and got the same result. Any help?
-
What is the difference between == and = ?
--
Mats
-
You made a typographical error: num=0 should be num==0. But since 0 is an integer, your output in that case does not make sense. Also, unless I missed something, num % 1 != 0 is always false.
A similiar problem with = versus == is repeated later in your program.
-
thank you
will apply changes. However, I'm still confused if a decimal/fraction is divided by one it is still the decimal, thus producing a remainder. This doesn't apply for %? Please clarify. I apreciate it.
-
Code:
cin >> num;
if(num=0 || num % 1 != 0)
{
cout << "Not an integer. Shutting down." << endl;
}
I thought 0 was an integer. Besides 0, num, being an integer variable, can't store anything that isn't an integer. If you want to check that the user indeed typed an integer, you'll need to test the result of the input statement:
Code:
if (!(cin >> num) || num == 0)
{
cout << "Not an integer. Shutting down." << endl;
}