• Java语言第四讲


    1.纯随机数发生器

    Xn+1=(aXn + c)mod m

    Modulus=2^31-1=int.MaxValue

    Multiplier=7^5=16807

    C=0

    当显示过2^31-2个数之后,才可能重复。

    动手动脑: 编写一个方法,使用以上算法生成指定数目(比如1000个)的随机整数。

    package 纯随机数;    
    public class Suiji
    {
            private static final int N = 200;
            private static final int LEFT = 40;
            private static final int RIGHT = 1000;
            private static long x0 = 1L;
            private long a = 1103515245L;
            private long c = 12345L;
            private long m = 2147483648L;
            // 产生随机数
            private long rand ( long r )
            {
              // a,c,m为常数
              r = ( r * a + c ) % m;//Xn+1=(aXn + c)mod m线性同余生成器
              return r;
            }
            /*表示a~b之间的一个随机数*/
            private long little ( int a, int b, long rand )
            {
              return a + rand % ( b - a + 1 );
            }
            private void recursion ( int count, long rand )
            {
             if (count >= N)
             {return;}
             rand = rand (rand);
             long r = little (LEFT, RIGHT, rand);
             System.out.print (r + " ");
             recursion (++count, rand);
            }
            public static void main ( String[] args )
            {
             Suiji recur = new Suiji ();
             recur.recursion (0, x0);
            }
    }

    2.动手动脑:

    请看以下代码,你发现了有什么特殊之处吗?

    // MethodOverload.java
    // Using overloaded methods
    public class MethodOverload {
    
        public static void main(String[] args) {
            System.out.println("The square of integer 7 is " + square(7));
            System.out.println("
    The square of double 7.5 is " + square(7.5));
        }
    
        public static int square(int x) {
            return x * x;
        }
    
        public static double square(double y) {
            return y * y;
        }
    }

    结果:

    The square of integer 7 is 49

    The square of double 7.5 is 56.25

    特殊之处:

    上述示例代码展示了Java的“方法重载(overload)”特性。 满足以下条件的两个或多个方法构成“重载”关系:

    (1)方法名相同; (2)参数类型不同,参数个数不同,或者是参数类型的顺序不同。 注意:方法的返回值

    不作为方法重载的判断条件。

  • 相关阅读:
    杭电acm1517
    杭电acm1228
    杭电acm1859
    杭电acm1124
    杭电acm1327
    CPP Templates 之 template 关键字的用法技巧
    malloc与calloc区别
    CPP Templates 之 类模板的继承
    CPP Templates 之 模板演绎的注意事项
    CPP Templates 之 局部类模板特化
  • 原文地址:https://www.cnblogs.com/bailanglang/p/5965435.html
Copyright © 2020-2023  润新知