Java 为什么不能将Math.max和Math.min相加或相减?
我正在试图弄清楚为什么Math.max和Math.min不起作用。 我知道如果我想的话,我也可以使用和if-else语句,但是有没有一种方法可以不用if-else来实现呢Java 为什么不能将Math.max和Math.min相加或相减?,java,math,Java,Math,我正在试图弄清楚为什么Math.max和Math.min不起作用。 我知道如果我想的话,我也可以使用和if-else语句,但是有没有一种方法可以不用if-else来实现呢 Scanner Scan = new Scanner(System.in); System.out.println("Enter three integers(Use enter in between): "); int x = Scan.nextInt(); int y = Scan.nex
Scanner Scan = new Scanner(System.in);
System.out.println("Enter three integers(Use enter in between): ");
int x = Scan.nextInt();
int y = Scan.nextInt();
int z = Scan.nextInt();
System.out.println(
Math.min(x, Math.min(x, z))+", " // Prints the minimum of {x, z}
+Math.max(x, Math.max(y, z))+", " // Prints the maximum of {x, y, z}
+(
Math.max(x, Math.max(y, z)) // Get the max of {x, y, z}
+Math.min(x, Math.min(y, z)) // Get the min of {x, y, z}
// Sum should be the sum of smallest and largest of {x, y, z}
) // Convert to string
+(-x-y-z) // The sum of -1 * x+y+z, converted to String
); // println
在我看来,一旦将Math.min(x,Math.min(x,z))
更改为Math.min(x,Math.min(y,z))
请解释你所说的“不工作”是什么意思。我向你保证
Math.max
和Math.min
工作正常。你得到的是什么输出,它与你期望它做的有什么不同?这部分是无用的Math.min(x,Math.min(x,z))
:如果z
是min,那么用x
第二次做min并不重要。如果x
是最小值,那么您只需执行min(x,x)
。如果您需要两次相同的操作(x,y和z的最小值/最大值),请使用变量。可能有助于清理此问题。如果与+
运算符一起使用的任何变量是字符串
,则+
将像字符串串联一样工作。所以如果你有System.out.println(1+“,+2+3)代码>它将导致1,23
不在1,5
中。要获得1,5
,您需要使用如下括号System.out.println(1+”,“+(2+3))