function keeps crashing my program???

Started by
10 comments, last by Driv3MeFar 17 years, 6 months ago
Did you check out the links posted by Emmanuel Deloget?
Basically the lowest bit is anded with 1 (another way of saying is the lowest bit on)if this is true then its an odd number else its even.
[edit]
But I would agree with Conner McCloud.
Advertisement
Quote:Original post by aaroncox_123
Thanks for posting...

I found that changing the for loop didnt make any difference ie: i += 2.

could someone please explanin return(value & 1);

thanks.


Assuming thats all you changed from your original post:
#include <iostream>using namespace std;bool EvenNo(int value);int main(){	int x;	cout<<"Please enter a number -->";	cin>>x;	if(EvenNo(x) == true)	{		cout<< x << " is an even number"<<endl;	}	else	{		cout<< x << " is an odd number"<<endl;	}	system("pause");	return 0;}bool EvenNo(int value){	int val = value-1;	for (int i = 0; i <= value; i += 2)	{		if(i == val)		{			return false;		}	}	return true;}


This works fine for me in MSVS 2005.

Does your program hang (ie become irresposive) or crash? If it crashes, does it display an error message? Have you tried debugging through your program?

Edit:
I, too, agree with Conner McCloud that you should inderstand this code before learning things like bitwise arithmetic, but since you asked:

Computers represent numbers in binary, a base 2 number system (ie, consiting only of 0 and 1). Basically, a binary number is a string of 0's and 1's, where each consecutive digit represents the next highest power of two:
______________________________________| 1 | 2 | 4 | 8 | 16 | 32 | 64 | 128 |  <--powers of 2--------------------------------------| 1 | 0 | 1 | 0 | 1  | 1  | 0  |  0  |  <--a base-2 number--------------------------------------


Above would be the base-10 (decimal) number 53, as can be seen by adding together all the numbers above the '1' digits.

As you can see, since the first digit in binary represents a 1 in base ten, any binary number with that first digit set will be odd.

Now, we come to the bitwise AND (&) operator. A bitwise takes two binary numbers, and if the same bit is set in both, it sets that bit in the resulting number. By ANDing with 1, we basically are asking if the first bit is set in the number being ANDed, which, as explained above, will indicate if the number is odd or even.

Not the best explanation, but hopefully you understand. Check Emmanuel Deloget's links for a clearer explanation.

This topic is closed to new replies.

Advertisement