[英]using Math.max to replace only negative numbers
我正在制作一个基于用户输入进行计算的程序,并且应该在不使用“if 语句”或“:?”的情况下将负数更改为默认值。 我曾尝试使用 Math.max(input,1),但是,这会给 0 和 1 之间的值带来问题。有什么建议吗?
也许是一个愚蠢的解决方案,但试试这个:
while (input < 0)
input = 1;
好吧,我能想到一种非常可怕的做法。 它依赖于使用Math.signum
,负输入返回 -1.0,正输入返回 1.0,零输入返回 0。 我们可以使用Math.min(Math.signum(input, 0))
得到 -1.0 表示负输入,0 表示零或正输入。
这样,我们可以将输入钳位到最小值为零,然后减去“-1.0 或 0”以避免更改任何非负输入,但将负输入转换为 1。
这是执行此操作的完整代码:
public class Test {
public static void main (String[] args) {
testValue(-1.5);
testValue(-0.5);
testValue(0);
testValue(0.5);
testValue(1.5);
}
private static void testValue(double input) {
double result = transformInput(input);
System.out.println(input + " -> " + result);
}
private static double transformInput(double input) {
double clampedValue = Math.max(input, 0);
double clampedSign = Math.min(Math.signum(input), 0);
return clampedValue - clampedSign;
}
}
但正如我在评论中指出,这是一个可怕的问题,这是更好地与实现?:
运营商,我怀疑谁设置你这个任务的智慧。
绝对没有我想要的那么干净(即使我不喜欢它有多么复杂),但它有效;)
Math.round(((Math.max(input+1, 1)-Math.signum(input+Math.abs(input)))*100))/100.0
输入
5
0.5
0.3
-0.2
-0.5
-2
输出
5.0
0.5
0.3
1.0
1.0
1.0
您可以使用自己的方法来实现您的逻辑并返回所需的结果,而不是使用Math.max(..,..)
,如下所示。
public static double mapInput(double input) {
return Math.max(input, (input < 0 ? 1 : input));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.