我需要在用户指定的任意两个值之间生成指定数量的随机整数(例如,12 个数字都在 10 到 20 之间),然后计算这些数字的平均值。问题是如果我要求它生成 10 个数字,它只会生成 9(显示在输出中)。另外,如果我输入最大范围 100 和最小范围 90,程序仍然会生成 # 像 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