#### Archived

This topic is now archived and is closed to further replies.

# How do I check if 2 numbers are oppositely signed in C++

This topic is 6098 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

How do I check if two numbers have the same sign or not. I may be missing something pretty obvious, but please help. Oh btw. I would like the fastest way plz. Thx

##### Share on other sites
 int a = -7;int b = 3;if((a < 0 && b >= 0) || (a >= 0 && b < 0)) cout << "The numbers have opposite signs";

Hopefully this wasn''t a homework assignment...

Cheers

##### Share on other sites
The mechanism you use depends on how tied to the hardware you want to be, and what kinds of numbers you're talking about.

Edited by - DrPizza on February 3, 2002 9:41:56 PM

##### Share on other sites
By sign do you mean +/- ? If so you simply need to do two tests to see if each number is > or < (or = to) 0. Then compare the two results. Here''s an example in C++:

// returns true if a and b have same sign, otherwise returns false
void sameSign(int a, int b){
if (a < 0 && b < 0)
return true;
else if (a > 0 && b > 0)
return true;
else if (a == 0 && b == 0)
return true;
else
return false;
}

"I''''m not evil... I just use the power of good in evil ways."

##### Share on other sites
Multiply them and look at the result,
if the result is positive, they have the same sign,
if the result is negative, they have opposite signs.

##### Share on other sites
You''re right. It''s pretty obvious.

How do we know that 5 and 8 have the same sign? Because they''re both greater than 0.

How do we know that -3 and -6 have the same sign? Because they''re both less than 0.

DOH. Just looked down and saw that a billion people have already replied. No use in driving it in any more

##### Share on other sites
wow i like roland''s idea the most. that''s creative.

##### Share on other sites
For 32bit processors (and 32bit signed numbers) only:
 if( (a & 0x80000000) ^ (b & 0x80000000) ) { /* The numbers have opposite signs. */} else { /* The numbers have the same sign. */}

##### Share on other sites
Or a variation of my last one:
 if( (a ^ b) & 0x80000000 ) { /* They have opposite signs */}

##### Share on other sites
The only thing is his method doesn''t handle zero''s very well. While 3 and 0 have different signs (3*0 = 0), two zeros technically have the same sign, but 0*0 = 0 would suggest they are different. It all depends on how you want to handle such a function.... why you would need one that does this is beyond me though.

Hehe, I too was surprised by the quick responses to this post =-)

"I''''m not evil... I just use the power of good in evil ways."

1. 1
Rutin
26
2. 2
3. 3
4. 4
5. 5

• 9
• 13
• 19
• 14
• 9
• ### Forum Statistics

• Total Topics
632940
• Total Posts
3009329
• ### Who's Online (See full list)

There are no registered users currently online

×