2017-08-05 73 views
1

我只是在使用隨機數和平均數來自己練習java編程,但是我很難做到這一點。該程序將要求「輸入#在0到100之間滾動」。然後我輸入'3',那麼輸出將是隨機的3個數字。 我的問題是3個數字出來後,我想找到這些數字的平均值。例如,我希望我的輸出是Java基本平均數和隨機數

Your # is 89 
Your # is 50 
Your # is 12 
Your avg is ##(//whatever the avg of numbers) 

我的輸出類似

Enter # to be rolled between 0 to 100 
3 
Your # is 89 
your avg is 29 
Your # is 39 
your avg is 13 
Your # is 76 
your avg is 25 

你們能幫助我解決這個問題呢?我知道我的代碼亂七八糟。

import java.util.Random; 
import java.util.Scanner; 

public class ranEx { 

    public static void main(String[] args) { 

     Random ranNumber = new Random(); 
     Scanner input = new Scanner(System.in); 

     int number; 
     int ran; 

     System.out.println("Enter # to be rolled " 
       + "between 0 to 100"); 
     number = input.nextInt(); 

     for(int i=0; i<number; i++) { 
      ran=ranNumber.nextInt(100); 

      System.out.println("Your # is " + ran); 


      int avg=ran/number; 

      System.out.println("your avg is " + avg); 

     }  

    } 

} 
+1

您不計算平均值,您將隨機數除以數值。 –

+0

如果您只想要平均值,請定義一個保持累計總量的變量,然後除以滾動次數。 –

+1

Average =總數/次數 – theisuru

回答

0

您需要定義avg外循環,然後所有的號碼添加到它。最好將它稱爲sum並將其定義爲double以防止四捨五入,這樣您可以在迴路後將它除以number並獲得平均值。

double sum = 0; 
for(int i=0; i<number; i++) { 
// ... 
    sum += ran; 
} 
System.out.println("your avg is " + sum/number); 
0
int sum=0; 
for(int i=0; i<number; i++) { 
      ran=ranNumber.nextInt(100); 

      System.out.println("Your # is " + ran); 

      sum = sum+ran; 

     }  
     System.out.println("your avg is " + sum/number);  
0

它的測試: 用戶必須輸入一個數字整數

import java.util.Random; 
import java.util.Scanner; 
public class ranEx { 
public static void main(String[] args) { 
    Random ranNumber = new Random(); 
    Scanner input = new Scanner(System.in); 
    int number; 
    int ran = 0; 
    System.out.println("Enter A NUMBER to be rolled " 
      + "between 0 to 100"); 
    number = input.nextInt(); 
    for(int i=0; i<number; i++) { 
     ran=ran+(ranNumber.nextInt(100)); 
     System.out.println("Your # is " + ran); 
     int avg=ran/number; 
     System.out.println("your avg is " + avg); 
    }  
    } 
} 

輸出:

run: 
Enter A NUMBER to be rolled between 0 to 100 
5 
Your # is 95 
your avg is 19 
Your # is 107 
your avg is 21 
Your # is 178 
your avg is 35 
Your # is 274 
your avg is 54 
Your # is 338 
your avg is 67 
BUILD SUCCESSFUL (total time: 2 seconds) 
0

你要計算平均只有一次,的循環之後,循環生成值。你可以實現你的目標如下:

  1. Intialize累加器變量循環
  2. 在循環中前爲零,每個生成的值添加到累加器
  3. 後循環,分累加器值由值的數量
0

如果你只是想要的平均值,定義一個變量,保持累計總和,然後除以卷的數量。

// double for large values and decimal division later on 
double total= 0; 

int rolls = 4; 
for (int x = 0 ; x < rolls; x++) { 

    total += x; 
} 

// calculate average 
double average = total/rolls; 

// validate that it works, ((0 + 1 + 2 + 3)/4) == 1.5 
Assert.assertEquals(1.5d, average);