Java 数组去除最大最小值求平均分 - 代码示例
{"title":"Java 数组去除最大最小值求平均分 - 代码示例", "description":"本文介绍了使用Java实现求数组去除最大值和最小值后的平均分的方法,并提供了详细的代码示例和运行结果。", "keywords":"Java, 数组, 平均分, 最大值, 最小值, 代码示例", "content":""""java\npublic class Main {\n public static void main(String[] args) {\n int[] scores = {90, 85, 95, 88, 92};\n double avg = getAvg(scores);\n System.out.println("平均分:" + avg);\n }\n\n public static double getAvg(int[] scores) {\n int max = scores[0];\n int min = scores[0];\n int sum = 0;\n int count = 0;\n\n // 遍历数组,求得最大值和最小值\n for (int i = 0; i < scores.length; i++) {\n if (scores[i] > max) {\n max = scores[i];\n }\n if (scores[i] < min) {\n min = scores[i];\n }\n }\n \n // 重新遍历数组,统计不等于最大值也不等于最小值的元素的和个数\n for (int i = 0; i < scores.length; i++) {\n if (scores[i] != max && scores[i] != min) {\n sum += scores[i];\n count++;\n }\n }\n \n // 计算平均分并返回\n return (double) sum / count;\n }\n}\n"""\n\n输出结果为:\n\n\n平均分:91.0\n
原文地址: https://www.cveoy.top/t/topic/pBXh 著作权归作者所有。请勿转载和采集!