Topic: 请教 随机数问题

  Print this page

1.请教 随机数问题 Copy to clipboard
Posted by: xingchao
Posted on: 2006-04-02 15:03

请问
怎样在一个给定的范围里随机的挑选几个数
例如 在1-100里随机的取15个数字。
该问题是不是要用Random 函数? 如果用该怎么用呢?
请各位多多帮助
谢谢!

2.Re:请教 随机数问题 [Re: xingchao] Copy to clipboard
Posted by: 我所爱
Posted on: 2006-04-02 15:40

本人也是初学,这是我的方法:

int[] a=new int[15];
for(int i=0;i<15;i++)
{
a[i]=(int)Math.random()*100;
}

有错请多指教

3.Re:请教 随机数问题 [Re: xingchao] Copy to clipboard
Posted by: Skybus
Posted on: 2006-04-02 19:53

int[] a = new int[15];
for (int i = 0; i < 15; i++)
a[i] = (int) (Math.random() * 100);

或者这样
import java.util.Random;

int[] a = new int[15];
Random rand = new Random();
for (int i = 0; i < 15; i++)
a[i] = rand.nextInt(100) + 1;

btw:这些问题应该在论坛上先搜索一下

4.Re:请教 随机数问题 [Re: 我所爱] Copy to clipboard
Posted by: why
Posted on: 2006-04-03 21:59

我所爱 wrote:
a[i]=(int)Math.random()*100;

a[i]=( (int)Math.random()*100 ) + 1;
否則只是 0 - 99

5.Re:请教 随机数问题 [Re: why] Copy to clipboard
Posted by: 我所爱
Posted on: 2006-04-05 12:30

why wrote:
a[i]=( (int)Math.random()*100 ) + 1;
否則只是 0 - 99


明白了,谢谢指点!

6.Re:请教 随机数问题 [Re: xingchao] Copy to clipboard
Posted by: fqwy
Posted on: 2006-04-07 09:25

Math.random()不是返回0.0-1.0的双精度数吗?
难道(int)Math.random()*100 )返回的不可能包括100吗?

7.Re:请教 随机数问题 [Re: fqwy] Copy to clipboard
Posted by: why
Posted on: 2006-04-07 22:34

fqwy wrote:
Math.random()不是返回0.0-1.0的双精度数吗?
难道(int)Math.random()*100 )返回的不可能包括100吗?

http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#random()
public static double random()
Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923