数据结构-2(随机数、对数器)

随机函数Math.random()

1.返回类型:double   

2.范围:[ 0,1)

3.特点:等概率返回区间内的数

import java.lang.Math;
public class Demo {
    public static void main(String[] args) {
        int testTimes=10000;//总测试次数
        int []counts=new int[9];//counts[i]代表i数字出现次数
        for(int i=0;i<testTimes;i++){
            int temp=(int)(Math.random()*9);//temp为[0,9)随机数
            counts[temp]++;
        }
        for(int i=0;i<9;i++){
            System.out.println(i+"出现了"+counts[i]+"次");
        }
    }
}

运行结果

介绍随机函数(不用Math.random)(面试常见)

条件1:函数f1()只能随机返回1-5的随机数

目标:随机返回1-7随机数

1-5随机-》0-6随机 解题思路

代码演示

import java.lang.Math;
public class Demo {
    //条件:返回1-5随机数
    public static int f1(){
        return (int)(Math.random()*5)+1;
    }
    //构造0-1发生器
    public static int f2() {
        int ans=0;
        do {
            ans=f1();
        }while(ans==3);
        if(ans==1||ans==2)return 0;
        else return 1;
    }
    //利用二进制构造0-7随机数生成器
    public static int f3(){
        return (f2()<<2)+(f2()<<1)+f2();
    }
    //利用f3()构造0-6随机数生成器
    public static int f4(){
        int ans=0;
        do{
            ans=f3();
        }while(ans==7);
        return ans;
    }
    public static void main(String[] args) {
        //测试f4()
        int testTimes=10000;
        int []counts=new int[7];
        for(int i=0;i<testTimes;i++){
            int temp=f4();
           counts[temp]++;
        }
        for(int i=0;i<7;i++){
            System.out.println(counts[i]);
        }
}
}

输出结果

Math下常见方法

算数运算

ps. a,b均为double类型

Math.abs(a):取a的绝对值

Math.sqrt(a):取a的平方根

Math.cbrt(a):取a的立方根

Math.max(a,b):取a、b之间的最大值

Math.min(a,b):取a、b之间的最小值

Math.pow(a,b):取a的b平方

算数进位

Math.ceil (double a):逢余进一,向上取整;

Math.floor(double a):逢余舍一,向下取整;

Math.rint(double a):四舍五入,返回double值;

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

三函数

a-角度,以弧度表示;

Math.sin(double a):正弦

Math.cos(double a):余弦

Math.tan(double a):正切

静态常量

Math.E  : e(自然对数)

Math.PI  : π

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值