求数组元素中的最大值、最小值、总和、平均值

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;
/*
* 	题目:定义一个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)
*/
public class ArrayTest04 {
   public static void main(String[] args) {
   	// 1.定义一个一维数组
   	int[] array = new int[10];
   	
   	// 2.遍历数组,进行随机赋值
   	for(int i = 0; i < array.length; i++){
   		array[i] = (int)(Math.random() * 90 ) + 10;
   		// 输出随机数
   		System.out.print(array[i] + " ");
   	}
   	
   	// 3.获取数组元素中得最大值
   	// 将数组中得第一个元素作为参考数,进行比较
   	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);
   	
   	// 4.获取数组元素中得最小值
   	int minValue = array[0];
   	for(int i = 1; i < array.length; i++){
   		if(array[i] < minValue){
   			minValue = array[i];
   		}
   	}
   	System.out.println("最小值:" + minValue);
   	
   	// 5.求总和
   	int sum = 0;
   	for(int i = 0; i < array.length; i++){
   		sum += array[i];
   	}
   	System.out.println("总和为:" + sum);
   	
   	// 6.求平均值
   	int avgValue = sum / array.length;
   	System.out.println("平均值为:" + avgValue);
   }
}

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值