在唱歌比赛中,有6名评委给选手打分,范围是【0-100】之间的整数。选手的最后得分为:去掉最高分,最低分之后的4个评委的平均分。
分析1.把6个评委的分数录入到程序中去(使用数组);
int[] scores = new int[6]
2.遍历数组中每个数据,进行累加求和,并找出最高分,最低分;
3.按照分数的计算规则算出平均分。
1.定义一个动态初始化的数组,用于后期录入6个评委的分数
int[] scores = new int[6];
2.录入6个评委的分数(需要导入扫描器Scanner的包)
Scanner sc = new Scanner(System.in);
for (int i = 0; i < scores.length; i++) {
System.out.println("请输入第" + (i + 1) + "位评委的打分:");
int score = sc.nextInt();
}
3.把分数存入数组的对应位置处
scores[i] = score;
4.遍历数组中的每一个数据,找出最大值,最小值以及总分
int max = scores[0];
int min = scores[0];
int sum = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) {
//替换最大值变量存储的数据
max = scores[i];
}
if (scores[i] < min) {
//替换最小值变量存储的数据
min = scores[i];
}
//统计总分
sum += scores[i];
}
5.最后统计平均分即可
double result = (sum - max - min) * 1.0 / (scores.length - 2);
System.out.println("选手最终得分是:" + result);
完整代码
import java.util.Scanner;
public class Demo5 {
public static void main(String[] args) {
//1.定义一个动态初始化的数组,用于后期录入6个评委的分数
int[] scores = new int[6];
//2.录入6个评委的分数
Scanner sc = new Scanner(System.in);
for (int i = 0; i < scores.length; i++) {
System.out.println("请输入第" + (i + 1) + "位评委的打分:");
int score = sc.nextInt();
//3.把分数存入数组的对应位置处
scores[i] = score;
}
//4.遍历数组中的每一个数据,找出最大值,最小值以及总分
int max = scores[0];
int min = scores[0];
int sum = 0;
for (int i = 0; i < scores.length; i++) {
if (scores[i] > max) {
//替换最大值变量存储的数据
max = scores[i];
}
if (scores[i] < min) {
//替换最小值变量存储的数据
min = scores[i];
}
//统计总分
sum += scores[i];
}
//5.统计平均分即可
double result = (sum - max - min) * 1.0 / (scores.length - 2);
System.out.println("选手最终得分是:" + result);
System.out.println("最高分是:" + max);
System.out.println("最低分是:" + min);
}
}
运行结果
总结
1.定义一个动态初始化的数组用于存储分数数据;
2.定义三个变量用于保存最大值,最小值和总和;
3.遍历数组中的每个元素,依次进行统计;
4.遍历结束后按照规则计算出结果即可。



