簡體   English   中英

計算數組中隨機整數的平均值

[英]calculating average of random integers in an array

我需要在用戶指定的任意兩個值之間生成指定數量的隨機整數(例如,10到20之間的12個數字),然后計算數字的平均值。 問題是,如果我要求它生成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

Java數組基於零。 在這里,您將第一個數組元素保留為其默認值0 更換

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

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

編輯:回答問題(從現在刪除的評論)為什么這不會產生最小值和最大值之間的值

max * Math.random () + min

Math.random生成介於0.01.0之間的雙精度值。 因此,例如,最小值為90且最大值為100將產生介於90190之間的數字(!)。 要限制您需要的最小值和最大值之間的值

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

Java數組開始索引為0.此外,您的循環退出一個索引short。 因此,當n == 6時,您的條件是“x <= 5”,循環退出。 嘗試這個:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM