# 计算数组中随机整数的平均值calculating average of random integers in an array

``````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?");
c.println ("What is the maximum value for these numbers?");
c.println ("What is the minimum value for these numbers?");

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
``````

## 2 个回复2

### ===============>>#1 票数：3

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`之间的双精度值。 因此，例如，最小值为`90`且最大值为`100`将产生介于`90``190`之间的数字（！）。 要限制您需要的最小值和最大值之间的值

``````min + Math.random() * (max - min)
^    |_________________________|
|                 |
90       value between 0 - 10
``````

### ===============>>#2 票数：1

Java数组开始索引为0.此外，您的循环退出一个索引short。 因此，当n == 6时，您的条件是“x <= 5”，循环退出。 尝试这个：

``````for ( x = 0; x < n; x++ {
// stuff
}
``````