Java 减去两个整数,结果应至少为零

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5846226/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:05:30  来源:igfitidea点击:

Java subtract two ints, result should be a minimum of zero

java

提问by herpderp

I want to subtract one integer from another, and the result should floor at 0. So 2 minus 4 should equal 0. I could just do

我想从另一个整数中减去一个整数,结果应该是 0。所以 2 减 4 应该等于 0。我可以这样做

int result = x - y;
if (result < 0) result = 0;

But is there a more elegant way?

但是有没有更优雅的方式呢?

回答by Thomas Eding

int result = Math.max(0, x - y);

回答by Edwin Buck

While a lot of people are rushing out with Math.max(...)solutions, I'd like to offer a simple if statement.

虽然很多人都急于提出Math.max(...)解决方案,但我想提供一个简单的 if 语句。

if (y > x) {
  result = 0;
} else {
  result = x - y;
}

It is guaranteed to always return a result raised to 0, it doesn't require invoking an extra stack frame (entering the Math static function would), and it prevents underflow.

它保证总是返回一个升为 0 的结果,它不需要调用额外的堆栈帧(进入 Math 静态函数会),并且它可以防止下溢。

In the rare event that X is close to the minimum int, and y is sufficiently large enough, evaluating (x-y) would result in an underflow. The result would be "too large" of a negative number to fit in an int's space and would therefore roll into a nonsense (and probably positive) answer.

在 X 接近最小 int 且 y 足够大的极少数情况下,计算 (xy) 将导致下溢。结果将是“太大”的负数,无法放入 int 的空间,因此会变成无意义的(可能是肯定的)答案。

By forcing the if statement to guarantee no underflow exists, this solution is also more correct than the Math.max(...)solutions. However, most people don't care because they rarely deal with numbers that get close to causing overflows and underflows.

通过强制 if 语句保证不存在下溢,此解决方案也比Math.max(...)解决方案更正确。然而,大多数人并不关心,因为他们很少处理接近导致上溢和下溢的数字。

回答by Javed Akram

Use ternary operator ?:

使用三元运算符 ?:

int result = (x - y) > 0 ? (x - y) : 0;