我只是在使用隨機數和平均數來自己練習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);
}
}
}
您不計算平均值,您將隨機數除以數值。 –
如果您只想要平均值,請定義一個保持累計總量的變量,然後除以滾動次數。 –
Average =總數/次數 – theisuru