我创建了一个循环和随机数生成器,可以生成1-100范围内的100个数字。我需要格式化这些数字,使其每行为10。我尝试使用printf,但遇到了困难。此外,我必须找到所有这些数字的平均值。问题是我不确定如何做到这一点,因为所有的数字都在int变量"randoms"下。我不能把一个变量加在一起除以100。
public static void main(String[] args) {
Random rand = new Random();
int n = 100;
for (int i=1; i<=n; i++) {
int randoms = rand.nextInt(101);
}
}
您可以打印每一个数字,但不需要一行新行,在前面用空格填充4个长度的字符串,每10个值打印一行新行。对于平均值,使用数学:sum/count
Random rand = new Random();
int n = 100;
int total = 0;
for (int i = 1; i <= n; i++) {
int randoms = rand.nextInt(101);
total += randoms;
System.out.format("%4d", randoms);
if (i % 10 == 0) {
System.out.println();
}
}
System.out.println("AVG " + total / (double) n);
49 55 89 26 88 58 80 98 62 8
34 65 9 3 28 71 30 11 50 50
18 90 61 62 18 93 83 83 57 14
9 54 49 6 24 28 60 8 86 83
60 6 17 67 49 89 66 13 65 50
70 24 3 90 89 4 47 49 48 7
16 38 79 59 51 9 22 81 8 84
52 30 64 97 42 100 30 26 66 44
22 46 16 100 73 100 56 63 8 48
50 88 55 93 6 82 65 46 44 7
AVG 49.29