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

Started by
39 comments, last by executor_2k2 22 years, 2 months ago
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
Well, that was a waste of 2 minutes of my life. Now I have to code faster to get 'em back...
Advertisement
  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
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
char a[99999],*p=a;int main(int c,char**V){char*v=c>0?1[V]:(char*)V;if(c>=0)for(;*v&&93!=*v;){62==*v&&++p||60==*v&&--p||43==*v&&++*p||45==*v&&--*p||44==*v&&(*p=getchar())||46==*v&&putchar(*p)||91==*v&&(*p&&main(0,(char**)(--v+2))||(v=(char*)main(-1,(char**)++v)-1));++v;}else for(c=1;c;c+=(91==*v)-(93==*v),++v);return(int)v;}  /*** drpizza@battleaxe.net ***/
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."
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.
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
wow i like roland''s idea the most. that''s creative.
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.  */}  


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


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."

This topic is closed to new replies.

Advertisement