1.题目:定义一个int类型得一维数组,包含10个元素,随机赋值整数, 然后求出所有元素中得最大值,最小值,总和,平均值,并输出到控制台上。要求:所有随机数都是 2 位数
如何生成随机整数呢? 利用Math.random(),但是它得返回值是double类型得.
比如说生成[10,99]得随机整数:
-
公式为:(int)(Math.random() * (b - a + 1)) + a;
-
①Math.random(): [0.0,0.1)
-
②Math.random() * 90: [0.0,90.0)
-
③(int)(Math.random() * 90) [0,90)
-
④(int)(Math.random() * 90) + 10 [10,100)
package cn.xuguowen.exer;
public class ArrayTest04 {
public static void main(String[] args) {
int[] array = new int[10];
for(int i = 0; i < array.length; i++){
array[i] = (int)(Math.random() * 90 ) + 10;
System.out.print(array[i] + " ");
}
int maxValue = array[0];
for(int i = 1; i < array.length; i++){
if(array[i] > maxValue){
maxValue = array[i];
}
}
System.out.println();
System.out.println("最大值:" + maxValue);
int minValue = array[0];
for(int i = 1; i < array.length; i++){
if(array[i] < minValue){
minValue = array[i];
}
}
System.out.println("最小值:" + minValue);
int sum = 0;
for(int i = 0; i < array.length; i++){
sum += array[i];
}
System.out.println("总和为:" + sum);
int avgValue = sum / array.length;
System.out.println("平均值为:" + avgValue);
}
}