说到Java中的Math函数,大家肯定不陌生,但是在真正使用的时候却犯了难,那么多方法,我们到底需要使用哪个呢?
为此,我特地研究了一些Math常用函数的使用,以方便大家使用。
Math.sqrt()
: 计算平方根Math.cbrt()
: 计算立方根Math.pow(a, b)
: 计算a的b次方Math.max( , )
: 计算最大值Math.min( , )
: 计算最小值Math.abs()
: 取绝对值System.out.println(Math.sqrt(16)); // 4.0
System.out.println(Math.cbrt(8)); // 2.0
System.out.println(Math.pow(3, 2)); // 9.0
System.out.println(Math.max(2.3, 4.5));// 4.5
System.out.println(Math.min(2.3, 4.5));// 2.3
/**
* abs求绝对值
*/
System.out.println(Math.abs(-10.4)); // 10.4
System.out.println(Math.abs(10.1)); // 10.1
Math.ceil()
: 天花板的意思,就是逢余进一Math.floor()
: 地板的意思,就是逢余舍一Math.rint()
: 四舍五入,返回double值。注意.5的时候会取偶数Math.round()
: 四舍五入,float时返回int值,double时返回long值/**
* ceil天花板的意思,就是逢余进一
*/
System.out.println(Math.ceil(-10.1)); // -10.0
System.out.println(Math.ceil(10.7)); // 11.0
System.out.println(Math.ceil(-0.7)); // -0.0
System.out.println(Math.ceil(0.0)); // 0.0
System.out.println(Math.ceil(-0.0)); // -0.0
System.out.println(Math.ceil(-1.7)); // -1.0
System.out.println("-------------------");
/**
* floor地板的意思,就是逢余舍一
*/
System.out.println(Math.floor(-10.1)); // -11.0
System.out.println(Math.floor(10.7)); // 10.0
System.out.println(Math.floor(-0.7)); // -1.0
System.out.println(Math.floor(0.0)); // 0.0
System.out.println(Math.floor(-0.0)); // -0.0
System.out.println("-------------------");
/**
* rint 四舍五入,返回double值 注意.5的时候会取偶数 异常的尴尬=。=
*/
System.out.println(Math.rint(10.1)); // 10.0
System.out.println(Math.rint(10.7)); // 11.0
System.out.println(Math.rint(11.5)); // 12.0
System.out.println(Math.rint(10.5)); // 10.0
System.out.println(Math.rint(10.51)); // 11.0
System.out.println(Math.rint(-10.5)); // -10.0
System.out.println(Math.rint(-11.5)); // -12.0
System.out.println(Math.rint(-10.51)); // -11.0
System.out.println(Math.rint(-10.6)); // -11.0
System.out.println(Math.rint(-10.2)); // -10.0
System.out.println("-------------------");
/**
* round 四舍五入,float时返回int值,double时返回long值
*/
System.out.println(Math.round(10)); // 10
System.out.println(Math.round(10.1)); // 10
System.out.println(Math.round(10.7)); // 11
System.out.println(Math.round(10.5)); // 11
System.out.println(Math.round(10.51)); // 11
System.out.println(Math.round(-10.5)); // -10
System.out.println(Math.round(-10.51)); // -11
System.out.println(Math.round(-10.6)); // -11
System.out.println(Math.round(-10.2)); // -10
【注意】这里有一个非常需要注意的一点是:这里所有进位的方法的入参都要保证是float或者double类型,否则进位方法将毫无意义。例如如下我们经常犯的错误:
int a = 1300, b = 1000;
System.out.println(Math.ceil(a / b)); // 1 表达式A(错误使用)
System.out.println(Math.ceil(a / (float)b)); // 2 表达式B(正确使用)
看上去表达式A和表达式B没有什么区别,可仔细分析可知:a / b = 1 ,而 a / (float)b = 1.3, 实际上表达式A的Math.ceil()根本起不了任何作用。
Math.random()
: 取得一个[0, 1)范围内的随机数System.out.println(Math.random()); // [0, 1)的double类型的数
System.out.println(Math.random() * 2);//[0, 2)的double类型的数
System.out.println(Math.random() * 2 + 1);// [1, 3)的double类型的数
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blog.csdn.net/xuexiangjys/article/details/79849888
内容来源于网络,如有侵权,请联系作者删除!