简体   繁体   中英

calculating average of random integers in an array

I need to generate a specified number of random integers between any two values specified by the user (example, 12 numbers all between 10 and 20), and then calculate the average of the numbers. The problem is if I ask for it to generate 10 numbers, it will only generate 9 (shown in output.) Also, if I enter a max range of 100 and min range of 90, the program will still generate #'s like 147, etc that are over the max range... did I mess up the random number generator? Can someone help?

Here is the code I have so far:

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 arrays are zero based. Here you leave the first array element at its default value of 0 . Replace

for (x = 1 ; x <= n-1 ; x++) 

with

for (x = 0 ; x < n ; x++) 

Edit: To answer question (from now deleted comment) of why this does not produce values between min and max

max * Math.random () + min

Math.random generates double values between 0.0 and 1.0 . So for example, a min of 90 and max of 100 would generate numbers between and 90 and 190 (!). To limit the values between the min and max you would need

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

Java arrays start indexing at 0. Also your loop is exiting one index short. So, when n==6, your condition is then, "x <=5", and the loop exits. Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM