问题描述
使用函数完成以下功能,并得到一个完整的可以运行的程序:
1)输入若干个学生成绩,形成一个成绩数组,数量自己定。
2)统计成绩的最高分和最低分以及平均分
3)统计成绩的每个分数段所占比例。(不及格,中等,良好和优秀)
4)计算该班级成绩的方差。(方差为每个成绩减去平均分的差的平方之和)
代码实现
//导入包(根据包名修改)
package JavaMiddleTest;//包名
import java.util.Scanner;
public class QuestionOne {
public static void main(String[] args) {
//1.创建数组,存入成绩
double[] scores = new double[getScoreNumber()];
scores = inScore(scores);
//2.最大值
System.out.println("成绩最大值为:" + maxScore(scores));
//3.最小值
System.out.println("成绩最小值为:" + minScore(scores));
//4.平均值
System.out.println("成绩平均值为:" + averageScore(scores));
//5.成绩占比
scorePercent(scores);
//6.成绩方差
System.out.println("方差为:" + scoreDiffValue(scores));
}
//1.定义数组数量
public static int getScoreNumber(){
Scanner scanner = new Scanner(System.in);
System.out.println("输入数组大小");
return scanner.nextInt();
}
//1.创建数组
public static double[] inScore(double[] scores){
Scanner scanner = new Scanner(System.in);
int i = 0;
System.out.println("请输入" + scores.length + "个成绩:");
while(i < scores.length){
double score = scanner.nextDouble();
scores[i] = score;
i++;
}
return scores;
}
//2.最大值
public static double maxScore(double[] scores){
double max = scores[0];
for (int j = 0; j < scores.length; j++) {
if(max < scores[j]){
max = scores[j];
}
}
return max;
}
//3.最小值
public static double minScore(double[] scores){
double min = scores[0];
for (int j = 0; j < scores.length; j++) {
if(min > scores[j]){
min = scores[j];
}
}
return min;
}
//4.平均值
public static double averageScore(double[] scores){
double sum = 0;
for (int j = 0; j < scores.length; j++) {
sum += scores[j];
}
return (double)sum/scores.length;
}
//5.成绩占比
public static void scorePercent(double[] scores){
int excellent = 0,good = 0,pass = 0,failed = 0;
for (int j = 0; j < scores.length; j++) {
double score = scores[j];
if(score >=90 && score <= 100) {
excellent++; //优秀人数
}else if(score >= 80){
good++; //良好人数
}else if(score >= 60){
pass++; //及格人数
}else if(score >=0){
failed++; //不及格人数
}
}
System.out.println("优秀比例为:" + (double)excellent/scores.length *100 + "%");
System.out.println("良好比例为:" + (double)good/scores.length *100 + "%");
System.out.println("及格比例为:" + (double)pass/scores.length * 100 + "%");
System.out.println("不及格比例为:" + (double)failed/scores.length * 100 + "%");
}
//6.成绩方差,方差=(平均值-
public static double scoreDiffValue(double[] scores){
double average = averageScore(scores); //获取成绩平均值
double sunDiff = 0; //方差值
for (int j = 0; j < scores.length; j++) {
sunDiff += (average - scores[j]) * (average - scores[j]); //计算方差
}
return sunDiff;
}
}
运行结果