java 将负数更改为0的java函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12941948/
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
java function that changes negative number to 0
提问by LordZardeck
Is there a built-in function in java that would convert any negative number to a 0? what i'm wanting to do is subtract number from a variable, and ensure that it doesn't go below 0. is this possible with built-in functions or would i have to write my own?
java中是否有内置函数可以将任何负数转换为0?我想要做的是从变量中减去数字,并确保它不低于 0。这可以通过内置函数实现还是我必须自己编写?
回答by Denys Séguret
You should use :
你应该使用:
Math.max(0, yourVar)
You don't need a built-in function for that.
您不需要为此使用内置函数。
回答by Kevin Ng
You do not need any function to turn a negative into a zero. You can use a conditional declaration of the variable and turned the negative value into a zero.
您不需要任何函数即可将负数变为零。您可以使用变量的条件声明并将负值变成零。
In a conditional declaration, what goes before the question mark is the condition. If the condition evaluates to true, the first value after the question mark would be assigned to the variable.
在条件声明中,问号之前是条件。如果条件评估为真,则问号后的第一个值将分配给变量。
If the condition evaluates to false, the value that goes after the column will be assigned to the variable. In the case below, a would be assigned the value of itself if it does not carry a value that is below zero.
如果条件计算结果为 false,则列之后的值将分配给变量。在下面的情况下,如果 a 不携带低于零的值,则将为其分配自身的值。
int a = -1;
a = a < 0? 0 : a;