Java从零开始学二十八(Math类和Random类)

一、Math概述

提供了常用的数学运算方法和两个静态常量E(自然对数的底数)和PI(圆周率)

二、常用方法

package com.pb.demo1;

public class MathTest {

    public static void main(String[] args) {
        System.out.println("求平方根:" + Math.sqrt(9.0));
        System.out.println("求两数的最大值:" + Math.max(10,30));
        System.out.println("求两数的最小值:" + Math.min(10,30));
        System.out.println("2的3次方:" + Math.pow(2,3));
        System.out.println("四舍五入:" + Math.round(33.6));
    System.out.println("生成0-1之间的随机数:"+Math.random()); } }

三、Random类

Random是随机数产生类,可以指定一个随机数的范围,之后可以任意产生在此范围中的数字。
No.
方法
类型
描述
1
public boolean nextBoolean()
普通
随机生成boolean值
2
public double nextDouble()
普通
随机生成double值
3
public float nextFloat()
普通
随机生成float值
4
public int nextInt()
普通
随机生成int值
5
public int nextInt(int n)
普通
随机生成给定最大值的int值
6
public long nextLong()
普通
随机生成long值
 
package com.pb.demo1;

import java.util.Random;

public class RandomTest {

    public static void main(String[] args) {
        Random random=new Random();
        for (int i = 1; i <=10; i++) {
            System.out.println(random.nextInt(i));
            
        }
    }

}
原文地址:https://www.cnblogs.com/liunanjava/p/4301599.html