如何在数组中生成随机双打? [英] How do I generate random doubles in an Array?
问题描述
我的目标是向用户询问数组长度,并生成一个随机双精度列表以填充该数组.我不明白如何将Math.random放入我的数组中.我从另一种方法开始,然后废弃了它.为什么要使用double random = Math.random()* array;不能将随机生成器导入到我的数组中?
My goal is to ask the user for an array length and generate a list of random doubles to fill that array out. I don't understand how to get Math.random into my array. I started with a different approach and scrapped it. Why does double random = Math.random() * array; not import a random generator into my array?
import java.util.Scanner;
import java.util.Arrays;
import java.util.Random;
public class Average
{
public static void main(String[] args)
{
/*Scanner in = new Scanner (System.in);
System.out.println("Please enter your array size: ");
int size = in.nextInt();
int[] awnser = new int[size]; */
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
double[] array = new double[scanner.nextDdouble()];
double random = Math.random() * array;
System.out.println(array.length);
}
}
推荐答案
为什么双重随机= Math.random()*数组;不能将随机生成器导入到我的数组中?
Why does double random = Math.random() * array; not import a random generator into my array?
您误解了该类的工作原理.此处很好地解释了此类的作用.我相信您正在尝试执行以下操作:
You have misunderstood how this class works. Here is a good explanation of what this class does. What I believe you are trying to do is something along the lines of:
Random rand = new Random();
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a number");
//create an array with the size entered by the user
double[] array = new double[scanner.nextInt()];
//populate the array with doubles
for(int i =0; i < array.length; i++) {
array[i] = rand.nextDouble();
}
nextDouble
返回0到1.0之间的伪随机数,因此您需要将其乘以上限.(即,如果100是您的上限 rand.nextDouble()* 100;
)
nextDouble
returns a pseudorandom number between 0 and 1.0, so you'll need to multiply it by your upper bound. (i.e if 100 was your upper limit rand.nextDouble() * 100;
)
(Make sure to import
the Random
class)
这篇关于如何在数组中生成随机双打?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!