Java min 函数是 Math 库函数之一,用于返回给定两个参数中的最小值。该编程语言中 Math.min 的基本语法如下所示。
Math.min(data_type x, data_type y);
Java 编程提供了四种不同的 min 函数来查找给定两个参数中的最小值。以下函数将接受正整数或负整数值作为第一个和第二个参数,并返回整数类型中的较小值。
static int min(integer x, intger y); //Return Type is Integer // In order to use in program: Math.min(int x, int y);
类似地,此数学 min 函数接受 double、float 和 long 数据类型的负值或正值,并返回给定数据类型中的较小值。
static double min(double x, double y); //Return Type is double Math.min(double x, double y); static float min(float x, float y); //Return Type is float Math.min(float x, float y); static long min(long x, long y); //Return Type is long Math.long(long x, long y);
Java min 函数示例
在此示例中,我们使用 Math.min 函数查找不同数据类型中的最小值,并显示输出。
首先,我们直接对正整数值和负整数值都使用了它。前三个语句将调用 int 类型的静态 int min(int a, int b) 方法,并找出值中较小的一个。
接下来,我们将 Math.min 函数用于变量 b、c、d 和 e(它们属于 double 类型)。接下来的三个语句将调用 double 类型的(静态 double min(double a, double b))方法,并找出值中较小的一个。
接下来,我们将该函数用于变量 g、h、i 和 j(它们属于 float 类型)。接下来的三个 System.out.println 语句将调用 float 类型的(静态 float min(float a, float b))方法,并找出值中较小的一个。
最后,我们将此 数学函数 用于变量 k、l、m 和 n(它们属于 long 类型)。最后三个语句将调用 long 类型的(静态 long min(long a, long b))方法,并找出值中较小的一个。
public class MinMethod {
public static void main(String[] args) {
double b = 10.9666, c = 14.6674, d = -9.474, e = -14.9865;
float g = 1.23f, h = 4.809f, i = -7.89f, j = -6.54f;
long k = 200, l = 400, m = -300, n = -100;
System.out.println("Minimum value of Positive Integer: " + Math.min(10, 20));
System.out.println("Minimum value of Negative Integer: " + Math.min(-20, -60));
System.out.println("Minimum value of both Positive & Negative: " + Math.min(10, -20));
System.out.println("\nMinimum value of Positive Double: " + Math.min(b, c));
System.out.println("Minimum value of Negative Double: " + Math.min(d, e));
System.out.println("Minimum value of both Positive & Negative: " + Math.min(b, e));
System.out.println("\nMinimum value of Positive Float: " + Math.min(g, h));
System.out.println("Minimum value of Negative Float: " + Math.min(i, j));
System.out.println("Minimum value of both Positive & Negative: " + Math.min(h, i));
System.out.println("\nMinimum value of Positive Number: " + Math.min(k, l));
System.out.println("Minimum value of Negative Number: " + Math.min(m, n));
System.out.println("Minimum value of both Positive & Negative: " + Math.min(k, n));
}
}
