comparing two floats to see if they're both negative, or both positive

久未见 提交于 2019-12-12 18:58:46

问题


Hay guys, i have 2 floats, which both comes from input boxes.

I need to compare these 2 floats, if one is negative and one is positive thrown an error. If they're both positive, or both negative, thats fine.

Any ideas?

Thanks


回答1:


Multiply them together.

If the answer is positive then they are both the same sign.

If the answer is negative then they are of opposite sign.

If the answer is zero (within some value to take care of rounding error) then one or both are zero and you'll have to check them individually. You'll then have to decide whether 0 to be treated as positive or negative in your scenario.




回答2:


Although detection of the sign of the product can be done, it's not what you are interested in. Especially if you're going to use it on large volumes of floats (eg to detect a zero crossing in a time stream).

The simplest way is to exactly express what you ask for: is the sign of a equal to the sign of b?

function samesign( a, b ) {
  var aPositive = a >= 0;
  var bPositive = b >= 0;
  return aPositive == bPositive;
}

Or shorter:

function samesign( a, b ) { return (a>=0) == (b>=0); }



回答3:


Just do something like:

if float1*float2<0
    Error



回答4:


function isSameSign(a,b){
  var r = a*b; 
  return (r >= 0)
}


来源:https://stackoverflow.com/questions/2013680/comparing-two-floats-to-see-if-theyre-both-negative-or-both-positive

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!