如何在 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