通过数组解决:最大值 最小值 平均值 总值

package part03数组;


import java.util.Scanner;


/**
 * 通过数组解决:最大值 最小值 平均值 总值
 * @author Administrator
 *
 */
public class T02练习讲解1 {


public static void main(String[] args) {

//1 控制台输入10个学生的成绩,计算最高分,最低分,总分,平均分并输出
int score[] = new int[3];
int sum = 0;
Scanner sc = new Scanner(System.in);
//对数组元素赋值
for (int i = 0; i < score.length; i++) {
System.out.println("请输入第" +(i+1)+ "个成绩:");
//接收分数放到元素指定的位置
score[i]=sc.nextInt();
//累加:
sum += score[i];
}

//输出总分和平均分
System.out.println("总分:" + sum  + "  平均分:"  + (sum / score.length));


//最大值和最小值
//假设:假设数组中第一个元素就是最大值,也是最小值
int max = score[0];
int min = score[0];
for (int i = 1; i < score.length; i++) {
if (score[i] > max) {
//交换
max = score[i];
}

if (score[i] < min) {
//交换
min = score[i]; 
}
}

System.out.println("最大值:"  + max  +"  最小值:" +  min);

}
}

猜你喜欢

转载自blog.csdn.net/phoneix123/article/details/80841307
今日推荐