+ 1
Even and odd c++
5 Antworten
+ 2
bool isEven(int val) {
if(val%2 == 0)
return true; //Even...
return false; //Odd...
}
0
thanks
0
@Mara, please note you have a mistake in your program, and to compensate for this you test incorrectly for odd/even. Thus it looks like your program gives correct results, but it is because you actually do 2 wrong comparisons and then, since !false == true you end up with the right result.
You do this conditional test 1st:
if(isOdd(integer) == false)
.... " is odd." ...
If your isOdd function returns false, you output "is odd", which is incorrect.
Then, to compensate for this, you test for odd-ness like this:
if ( integer % 2== 0 )
That is how you actually test for even-ness! (there is no remainder if you divide an even number by 2).
Here is your program corrected:
int main (int argc, char *argv[])
{
int integer;
std::cout << "Please enter an integer: ";
std::cin >> integer;
if(isOdd(integer)){
std::cout << std::endl;
std::cout << integer << " is odd." << std::endl;
}else{
std::cout << std::endl;
std::cout << integer << " is even." << std::endl;
}
return 0;
}
bool isOdd( int integer ){
if ( integer % 2)
return true;
else
return false;
}