📜  Java Math min() 方法和示例

📅  最后修改于: 2022-05-13 01:55:22.403000             🧑  作者: Mango

Java Math min() 方法和示例

Java.lang.math.min()函数是Java中的一个内置函数,它返回两个数字中的最小值。参数采用 int、double、float 和 long。如果将负数和正数作为参数传递,则生成负数结果。如果传递的两个参数都是负数,则生成具有较高幅度的数字作为结果。
句法:

dataType min(dataType num1, dataType num2)
The datatypes can be int, float, double or long.

Parameters : The function accepts two parameters num1 and num2 
among which the minimum is returned

返回值:函数返回两个数字中的最小值。数据类型将与参数的数据类型相同。
下面给出了函数min() 的示例:

Java
// Java program to demonstrate the
// use of min() function
// two double data-type numbers are passed as argument
public class Gfg {
 
    public static void main(String args[])
    {
        double a = 12.123;
        double b = 12.456;
 
        // prints the minimum of two numbers
        System.out.println(Math.min(a, b));
    }
}


Java
// Java program to demonstrate the
// use of min() function
// when one positive and one
// negative integers are passed as argument
public class Gfg {
 
    public static void main(String args[])
    {
        int a = 23;
        int b = -23;
 
        // prints the minimum of two numbers
        System.out.println(Math.min(a, b));
    }
}


Java
// Java program to demonstrate
// the use of min() function
// when two negative integers
// are passed as argument
public class Gfg {
 
    public static void main(String args[])
    {
        int a = -25;
        int b = -23;
 
        // prints the minimum of two numbers
        System.out.println(Math.min(a, b));
    }
}


Java
import static java.lang.Math.min;
 
class GFG {
    public static void main(String[] args)
    {
        int a = 3;
        int b = 4;
        System.out.println(min(a, b));
    }
}


输出:

12.123

Java

// Java program to demonstrate the
// use of min() function
// when one positive and one
// negative integers are passed as argument
public class Gfg {
 
    public static void main(String args[])
    {
        int a = 23;
        int b = -23;
 
        // prints the minimum of two numbers
        System.out.println(Math.min(a, b));
    }
}

输出:

-23

Java

// Java program to demonstrate
// the use of min() function
// when two negative integers
// are passed as argument
public class Gfg {
 
    public static void main(String args[])
    {
        int a = -25;
        int b = -23;
 
        // prints the minimum of two numbers
        System.out.println(Math.min(a, b));
    }
}

输出:

-25

如果您想在代码中多次找到两个数字的最小值,那么每次编写完整的Math.min()往往很乏味。因此,一个更短且更省时的方法是直接将Java.lang.Math.min作为静态导入,然后只使用min()而不是完整的Math.min()

Java

import static java.lang.Math.min;
 
class GFG {
    public static void main(String[] args)
    {
        int a = 3;
        int b = 4;
        System.out.println(min(a, b));
    }
}
输出
3