比较两个浮点数,看看它们是都是负数还是都是正数

发布于 2024-08-16 23:33:04 字数 119 浏览 2 评论 0原文

嘿伙计们,我有 2 个浮动,它们都来自输入框。

我需要比较这两个浮点数,如果一个为负,一个为正,则会引发错误。如果它们都是积极的,或者都是消极的,那很好。

有什么想法吗?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

内心荒芜 2024-08-23 23:33:04

将它们相乘。

如果答案是肯定的,那么它们都是相同的符号。

如果答案是否定的,那么它们的符号相反。

如果答案为零(在某个值内以处理舍入误差),则其中一个或两个都为零,您必须单独检查它们。然后,您必须决定在您的场景中将 0 视为正数还是负数。

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.

深居我梦 2024-08-23 23:33:04

尽管可以检测乘积的符号,但这不是您感兴趣的。特别是如果您打算在大量浮点数上使用它(例如,检测时间流中的零交叉)。

最简单的方法是准确表达您的要求:a 的符号等于 b 的符号吗?

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

或者更短:

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

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); }
反话 2024-08-23 23:33:04

只需执行以下操作:

if float1*float2<0
    Error

Just do something like:

if float1*float2<0
    Error
无所谓啦 2024-08-23 23:33:04
function isSameSign(a,b){
  var r = a*b; 
  return (r >= 0)
}
function isSameSign(a,b){
  var r = a*b; 
  return (r >= 0)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文