如何在 Java 中查找两个数字的 min()?
Java 提供了一个称为“ java.lang.Math ”的系统库,用于广泛的便捷操作。从三角函数到对数函数,由于其功能多样,您可以使用该库提供的方法找到一个数的最小值/最大值甚至绝对值。Math.min() 方法
这是该方法的常规表示。
Math.min(a, b)
请注意,此函数接受两个相同类型的参数int、long、float或double。让我们看一下Math.min()方法的可执行示例,以了解它的有效使用。确保在 IDE 中运行脚本以验证输出。
示例 1
package com.math.min.core
public class MathMinMethod {
public static void main(String[] args) {
int leenasAge = 10;
int tiffanysAge = 15;
// example of min () function
int min = Math.min(leenasAge, tiffanysAge);
System.out.print("Who's the younger sister? ");
if (min < tiffanysAge)
System.out.print("Leena ------- Age " + leenasAge);
else
System.out.print("Tiffany ------- Age " + tiffanysAge);
}
}
输出
妹妹是谁?莉娜 ------ 10 岁
解释
在第 8 行,int min = Math.min(leenasAge, tiffanysAge);int min 存储min()函数返回的最小值。稍后我们使用该结果来查找较小的兄弟姐妹的年龄。示例 2
package com.math.min.core;
public class MathMinMethod {
public static void main(String[] args) {
double berriesSoldInKg = 15.6;
double cherriesSoldInKg = 21.3;
// example of min () function
double min = Math.min(berriesSoldInKg, cherriesSoldInKg);
System.out.println("What's the minimum weight sold?");
if (min != cherriesSoldInKg)
System.out.print("Berries: " + berriesSoldInKg + " kg");
else
System.out.print("Cherries: " + cherriesSoldInKg +"kg");
}
}
输出
最小销售重量是多少?浆果:15.6 公斤
GO TO FULL VERSION