我需要在任何之间生成指定数量的随机整数 用户指定的两个值(例如,12 个数字都在 10 到 20 之间),然后计算数字的平均值。 问题是如果我要求它生成 10 个数字,它只会生成 9 个(显示在输出中。) 此外,如果我输入最大范围 100 和最小范围 90,程序仍会生成超过最大范围的 #'s,如 147 等……我搞砸了随机数生成器吗?有人可以帮忙吗?
这是我目前的代码:
public class ArrayRandom
{
static Console c; // The output console
public static void main (String[] args)
{
c = new Console ();
DecimalFormat y = new DecimalFormat ("###.##");
c.println ("How many integers would you like to generate?");
int n = c.readInt ();
c.println ("What is the maximum value for these numbers?");
int max = c.readInt ();
c.println ("What is the minimum value for these numbers?");
int min = c.readInt ();
int numbers[] = new int [n];
int x;
double sum = 0;
double average = 0;
//n = number of random integers generated
for (x = 1 ; x <= n-1 ; x++)
{
numbers [x] = (int) (max * Math.random () + min);
}
for (x = 1 ; x <= n-1 ; x++)
{
sum += numbers [x];
average = sum / n-1);
}
c.println ("The sum of the numbers is: " + sum);
c.println ("The average of the numbers is: " + y.format(average));
c.println ("Here are all the numbers:");
for (x = 1 ; x <= n-1 ; x++)
{
c.println (numbers [x]); //print all numbers in array
}
} // main method
} // ArrayRandom class
最佳答案
Java 数组是从零开始的。这里您将第一个数组元素保留为默认值 0
。替换
for (x = 1 ; x <= n-1 ; x++)
与
for (x = 0 ; x < n ; x++)
编辑: 回答为什么这不会产生最小值和最大值之间的值的问题(来自现在已删除的评论)
max * Math.random () + min
Math.random生成介于 0.0
和 1.0
之间的 double 值。因此,例如,90
的最小值和 100
的最大值将生成介于 90
和 190
之间的数字(! ).要限制您需要的最小值和最大值之间的值
min + Math.random() * (max - min)
^ |_________________________|
| |
90 value between 0 - 10
关于java - 计算数组中随机整数的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072418/