数组练习-平均值和最大值
数组的length
属性用于记录数组中有多少个元素或存储单元,即记录数组的长度是多少。
int[] nums = new int[10];//声明一个int型数组并动态初始化其大小为10
System.out.println(nums.length);//显示当前数组的大小
输出:10
遍历数组
通俗的理解,遍历数组就是:把数组中的元素都看一遍。
示例如下:
int[] arr = {1,3,5,7,9};
for(int i = 0 ; i<arr.length; i++){
System.out.print(arr[i] + ",");
}
输出:1,3,5,7,9
如何求出最大值
package test;
import java.util.Scanner;
public class test3 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] scores = new int[sc.nextInt()];
//循环给数组赋值
for(int i = 0 ; i< scores.length;i++){
scores[i] = sc.nextInt();
}
/********** Begin **********/
//在这里计算数组scores的平均值和最大值
int ps = 0;
for (int a = 0;a < scores.length; a++){
ps = ps + scores[a];
}
int max = scores[0];
for(int j = 0;j<scores.length;j++){
if(scores[j]>max){
max = scores[j];
}
}
System.out.println("平均值:" + (double)ps/scores.length );
System.out.println("最大值:" + max );
}
}
提示:
int a = 3;
int b = 2;
System.out.println(a/b);
System.out.println((double)a/b);