您的位置 首页 java

java Math类和Random类的用法

/**

* 测试Math类的常用方法

* 测试 Random

*/

public class TestMath {

public static void main(String[] args) {

int a = 4;

int b = -5;

int c = 2;

double d = 1.1;

double e = 1.5;

System.out.println(Math.abs(b)+”Math.abs()取绝对值 结果为5 返回结果为同数据类型”);

System.out.println(Math.sqrt(a)+”Math.sqrt()取 平方根 4开平方结果为2.0 返回double”);

System.out.println(Math.pow(c,a)+”Math.pow() 幂运算 返回c的a次方 结果为16.0 返回double”);

System.out.println(Math.max(a,c)+”Math.max()取两数最大值 结果为4 返回同数据类型”);

System.out.println(Math.min(a,c)+”Math.min()取两数最小值 结果为2 返回同数据类型”);

System.out.println(Math.ceil(d)+”Math.ceil()取大于d的最小整数 结果为2.0 返回double”);

System.out.println(Math.floor(e)+”Math.floor()取小于e的最大整数 结果为1.0 返回double”);

System.out.println(Math.random()+”取[0,1)的随机数 返回double 范围包含0不包含1″);

System.out.println(Math.round(e)+”Math.round()四舍五入 结果为2 返回long”);

System.out.println(Math.toDegrees(Math.PI)+”Math.toDegrees()将弧度转为角度 PI对应3.14 结果为180.0 返回double”);

System.out.println(Math.toRadians(45)+”Math.toRadians()将角度转为弧度 45度等于PI/4 结果为0.7853981633974483 返回double”);

System.out.println(Math.sin(Math.toRadians(30))+”Math.sin()求弧度的sin值 对边除以斜边 用Math.toRadians将30度转换为弧度 结果为0.49999999999999994 返回double”);

System.out.println(Math.cos(Math.PI/4)+”Math.cos()求弧度的cos值 邻边除以斜边 PI/4是45度 结果为0.7071067811865476 返回double”);

System.out.println(Math.tan(Math.PI/4)+”Math.tan()求弧度的tan值 对边除以邻边 结果为0.9999999999999999 返回double”);

System.out.println(Math.toDegrees(Math.asin(0.5))+”Math.asin()求arcsin值 通过已知sin值求弧度 返回double弧度 加toDegrees()转为角度 结果为30.000000000000004″);

System.out.println(Math.toDegrees(Math.acos(1/Math.sqrt(2)))+”Math.acos()求 arccos 值 返回double弧度 1除以根号2是45度 结果为45.00000000000001″);

System.out.println(Math.atan(3.0/4)+”Math.atan()求 arctan 值 返回double弧度 结果为0.6435011087932844″);

Random ran = new Random();

//Random类 用于产生随机数

System.out.println(ran.nextDouble()+”随机生成[0,1)的小数 作用同Math.random”);

System.out.println(ran.nextInt()+”随机生成int值 正负21亿之间随机取”);

System.out.println(ran.nextBoolean()+”随机生成true或者false”);

System.out.println(ran.nextInt(10)+”随机生成[0,10)区间的整数 不包含10 随机0-9″);

System.out.println(20+ran.nextInt(6)+”随机生成20-25的整数 .nextInt(6)是0-5 +20变成20-25″);

}

}

文章来源:智云一二三科技

文章标题:java Math类和Random类的用法

文章地址:https://www.zhihuclub.com/187513.shtml

关于作者: 智云科技

热门文章

网站地图