java学习中关于Math类的深层探究

    技术2022-07-11  126

    记录学习java路程将与风雨相伴!!!

    Math类(数学类)

    算术计算

    Math.sqrt():计算平方根

    Math.cbrt():计算立方根

    Math.pow(a,b):计算a的b次方

    Math.max(,):计算最大值

    Math.min(,):计算最小值

    Math.abs():取绝对值

    进位

    Math.ceil():天花板的意思,就是逢余进一

    Math.floor():地板的意思,就是逢余舍一

    Math.rint():四舍五入,返回double值。注意.5的时候会取偶数

    Math.round():四舍五入,float时返回int值,double时返回long值

    public class MathDemo{ public static void main(String argsu){ /** *abs求绝对值 */ System.out.printin(Math.abs(-10.4);//10.4 System.out.printin(Math.abs(10.1);//10.1 /** *ceil天花板的意思,就是返回大的值,注意一些特殊值 */ System.out.printin(Math.ceil(-10.1));//-10.0 System.out.printin(Math.ceil(10.7);//11.0 System.out.printin(Math.ceil(-0.7);//-0.0 System.out.printin(Math.ceil(0.0);//0.0 System.out.printin(Math.ceil(-0.0);//-0.0 /** *floor地板的意思,就是返回小的值 */ System.out.printin(Math.floor(-10.1);//-11.0 System.out.printin(Math.floor(10.7));//10.0 System.out.printin(Math.floor(-0.7);//-1.0 System.out.printin(Math.floor(0.0);//0.0 System.out.printin(Math.floor(-0.0);//-0.0 /** *max两个中返回大的值,min和它相反,就不举例了 */ System.out.printin(Math.max(-10.1-10));//-10.0 System.out.printin(Math.max(10.710);//10.7 System.out.println(Math.max(0.0-0.0));//0.0 /** *random取得一个大于或者等于0.0小于不等于1.0的随数 */ System.out.printin(Math.random0); //0.08417657924 System.out.printin(Math.randomO); //0.43527904004 /** *rint 四含五入,返回double值 *注意5的时候会取偶数 */ System.out.println(Math.rint(10.1);//10.0 System.out.printin(Math.rint(10.7);//11.0 System.out.printin(Math.rint(11.5);//12.0 System.out.printin(Math.rint(10.5);//10.0 System.out.println(Math.rint(10.51));//11.0 System.out.printin(Math.rint(-10.5));//-10.0 System.out.printin(Math.rint(-11.5);//-12.0 System.out.printin(Math.rint(-10.51));//-11.0 System.out.println(Math.rint(-10.6);//-11.0 System.out.printin(Math.rint(-10.2));//-10.0 /** *round 四舍五入,float时返回int值,double时返回long值 */ System.out.printin(Math.round(10.1);//10 System.out.println(Math.round(10.7);//11 System.out.printin(Math.round(10.5);//11 System.out.printin(Math.round(10.51));//11 System.out.printin(Math.round(-10.5);//-10 System.out.printin(Math.round(-10.51));//-11 System.out.println(Math.round(-10.6))://-11 System.out.printin(Math.round(-10.2);//-10 } }

    随机数

    Math.random():取得一个[0,1)范围内的随机数

    /**Math中,随机数的代码是:random.

    也就是 Math.random();

    这时一个 返回的是[0,1)double类型的值

    是一个伪随机数

    伪随机数就是按照一定规则去随机的数

    当需要打印多少范围到多少范围直接的随机整数时,会运用到一条公式

    公式: (最大值 - 最小值 +1 ) + 最小值 **/

    例如:

    //打印[5-10]的随机整数 int num = (int)(Math.random() * 6 + 5); //random本是double类型的,如果想打印整数类型(int)就需要将它强制转换成int类型 //这里的步骤 就是强制转换 //这里的* 6 + 5 是由 (10 - 5 + 1) + 5 这么来的 //也就是套用公式 System.out.println(num);//需求:随机20个[10-300]之间的数 打印最大值 int max = 0; for (int i = 0; i < 20; i++) {int num =(int) (Math.random()*291 + 10);if (max < num) { ​ max = num;} } ​ System.out.println(max);
    Processed: 0.010, SQL: 9