Math类常见的方法和Math类的Random

mac2025-10-30  14

Math类常见的方法和Math类的Random

/* * Math常见的方法 * Random r = new Random(); 使用默认当前系统时间的毫秒数作为种子数 * Random r = new Random(100) 使用自己指定的种子数 * 如果两个对象的参数相同,则生成的随机数相同(在一个for循环里面,种子数相同的两个对象,生成的随机数相同 */ import java.util.Random; public class MathRandom { public static void main(String[] args) { // TODO Auto-generated method stub // demo1(); demo2(); } private static void demo2() { //创建一个Random对象 Random r = new Random(); for(int i = 0; i < 5; i++) { System.out.println(r.nextInt()); } System.out.println("-------------"); Random r2 = new Random(100); Random r3 = new Random(100); // int a = r2.nextInt(); // int b = r2.nextInt(); // System.out.println(a); // System.out.println(b); for(int i = 0; i < 5; i++) { System.out.println(r2.nextInt()); //打印的两次的值一样 System.out.println(r3.nextInt()); } } private static void demo1() { System.out.println(Math.PI); //3.141592653589793 System.out.println(Math.random()); //随机数在0-1取 0.613681695289803 System.out.println(Math.sqrt(16)); //开平方根 4.0 System.out.println(Math.round(3.4)); //四舍五入 3 System.out.println(Math.round(3.6)); // 4 System.out.println(Math.pow(3.0, 3.0)); //立方数几的几次方 27.0 System.out.println(Math.floor(3.4)); //向下取整 3.0 System.out.println(Math.floor(3.6)); // 3.0 System.out.println(Math.ceil(3.4)); //向上取整 4.0 System.out.println(Math.ceil(3.6)); // 4.0 System.out.println(Math.abs(-2)); //取绝对值 2 } }

demo2结果:

1415374234 676172733 121443332 -301986470 1573867465 ------------- -1193959466 -1193959466 -1139614796 -1139614796 837415749 837415749 -1220615319 -1220615319 -1429538713 -1429538713
最新回复(0)