各种语言产生随机数的方法

C/C++:

 1     /*
 2     c++中不能用random
 3     rand()返回0--RAND_MAX之间均匀分布的伪随机整数,
 4     rand()不接收参数,随机数生成器总以相同的种子开始,默认以1为种子
 5     srand()可以指定不同的数为种子,
 6     RAND_MAX等于32767
 7     */
 8     const int MAX(100);
 9     srand((unsigned)time(NULL));//一个以当前时间开始的随机种子,应该放在循环语句前面
10     for (int i = 0; i != 20; i++)
11     {
12         cout << rand() % MAX << endl;//随机域为0~MAX-1
13         cout << "返回从0到最大随机数(RAND_MAX)的任意整数:" << rand() << endl;
14         cout << "产生0到10的整数:" << rand() % 11 << endl;
15         cout << "产生1到20的整数:" << 1 + rand() % 20 << endl;
16         cout << "产生5到100的整数:" << 5 + rand() % 96 << endl;//a+rand()%(b-a+1)表示a到b之间任意整数
17         cout << endl;
18     }

JAVA:

 1 public class JavaRandom {
 2 
 3     public JavaRandom()
 4     {
 5         System.out.println("Random实现");
 6         Random rand = new Random();//以当前时间为随机种子
 7         for(int i=0;i<10;i++)
 8             System.out.println(rand.nextInt());
 9     }
10     
11     void MathRand()//Math.round(Math.random()*(max-min)+min);
12     {               //0-10之间的随机数:(int)(Math.random()*10)
13         System.out.println("Math实现");
14         long num = Math.round(Math.random()*90+10);
15         System.out.println(num);
16         for(int i=0;i<10;i++)
17             System.out.println(Math.round(Math.random()*90+10));
18     }
19     public static void main(String[] args) {
20         new JavaRandom().MathRand();
21     }
22     
23 }

LUA实现:

 1 math.randomseed(os.time())
 2 for i=1,5  do
 3 
 4 print("第" .. i .. "遍")
 5 num = math.random(100,200)--        100~200
 6 print("随机数" .. num)
 7 
 8 num = math.random(100)    --           1~100
 9 print("随机数" .. num)
10 
11 num = math.random()       --               0~1
12 print("随机数" .. num)
13 
14 end

JavaScript实现:

 1 /*
 2 Math.round(value)//四舍五入
 3 Math.floor()    //向下取整
 4 Math.random()//产生0到1的随机数
 5 Math.floor(Math.random() * ( n + 1))//产生0到n的随机数
 6 Math.floor(Math.random()*(b-a+1) + a)  //产生a 到 b 的随机数 
 7 
 8 */
 9 //四舍五入
10 document.write(Math.round(4.7) + "<br />")
11 //向下取整
12 document.write(Math.floor(4.7) + "<br />")
13 //产生0到10的随机数
14 document.write(Math.floor(Math.random()*11)+ "<br />")

 

未完待续

 

posted @ 2015-10-25 11:15  露娜妹  阅读(574)  评论(0编辑  收藏  举报