课后作业

1.纯随机数发生器

 

 线性同余算法实现:

MyRandom类

public class MyRandom
{
    private static  final long multiplier=0x5DEECE66DL;

    private static final long modulus = 1L << 48;
    private static final long addend = 0xBL;

    private long seed;
    public void setSeed(long x){
        seed=x;
    }
    public int nextRandom() {

        this.seed = lcg(modulus, multiplier, addend, this.seed);
        return (int) (seed >>> 16);
    }

    protected long lcg(long m, long a, long c, long seed) {
        return (seed * a + c) % m;
    }



}

 

主函数rand类

import java.util.Scanner;

public class rand {
    public static void main(String[] args) {
        MyRandom mr=new MyRandom();
        System.out.print("请输入随机数个数:");
        int n;
        mr.setSeed(System.currentTimeMillis());
        Scanner sc=new Scanner(System.in);
        n=sc.nextInt();
        for(int i=0;i<n;i++){
            System.out.println(" "+mr.nextRandom());
        }

    }
}

  运行结果:

 种子由当前时间指定,会产生不同的随机数

2.函数重载

 square函数的形参的数据类型不同,发生了函数重载。

posted on 2023-09-20 18:09  Daniel350  阅读(5)  评论(0编辑  收藏  举报