CodeGym /Java 博客 /随机的 /Java Math.min() 方法
John Squirrels
第 41 级
San Francisco

Java Math.min() 方法

已在 随机的 群组中发布

如何在 Java 中查找两个数字的 min()?

Java 提供了一个称为“ java.lang.Math ”的系统库,用于广泛的便捷操作。从三角函数到对数函数,由于其功能多样,您可以使用该库提供的方法找到一个数的最小值/最大值甚至绝对值。

Math.min() 方法

这是该方法的常规表示。

Math.min(a, b)
请注意,此函数接受两个相同类型的参数intlongfloatdouble让我们看一下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 公斤

解释

在第 8 行, double min = Math.min(berriesSoldInKg, cherriesSoldInKg); 双“min”存储两个权重中的最低值。稍后,我们比较两个双打(以千克为单位)以检查两个水果中的最小值。在任何情况下都可以根据您的要求使用该结果。

结论

到现在为止,您应该能够理解Math.min()方法的必要性和效率。但是,如果有任何疑问或困惑,请随时再次查阅本文。不断成长和练习!
评论
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION