如何对我的数组的行和列求平均值?

huangapple go评论82阅读模式
英文:

How can I average the rows and columns of my array?

问题

我的程序获取一组学生的成绩。每行代表一个学生,每列代表一门考试。我需要计算每行的平均成绩(即每个学生的平均成绩),以及每门考试的总体平均成绩。我不知道该如何继续。

import java.util.Scanner;

public class students {
    private Scanner keyboard;
    private double[][] mat;

    public void classroom() {
        keyboard = new Scanner(System.in);
        System.out.println("你的教室有多少名学生?");
        // 我们知道有3门考试,但不知道教室里有多少名学生
        int rows = keyboard.nextInt();
        int columns = 3;
        mat = new double[rows][columns];
        for (int i = 0; i < mat.length; i++) {
            for (int c = 0; c < mat[i].length; c++) {
                System.out.println("请输入成绩");
                mat[i][c] = keyboard.nextDouble();
            }
        }
    }

    public void print() {
        for (int i = 0; i < mat.length; i++) {
            for (int c = 0; c < mat[i].length; c++) {
                System.out.print(mat[i][c] + " ");
            }
            System.out.println();
        }
    }

    public static void main(String[] args) {
        students e = new students();
        e.classroom();
        e.print();
    }
}
英文:

My program takes the grades of a group of students
the rows represent each student, while each column represents each of the exams.
I need the average for each row (that is, the average of grades for each student) just as I need the general average for each exam, I do not know how to continue.

import java.util.Scanner;
public class students
{ private Scanner keyboard;
    private double [][]mat;
    public void classroom(){
        keyboard = new Scanner (System.in);
        System.out.println(&quot;how many students does your classroom have?&quot;);
        //We know that 3 exams were done, but not how many students are in the classroom
        int rows = keyboard.nextInt();
        int columns = 3;
        mat= new double [rows][columns];
        for (int i=0; i&lt;mat.length;i++){
            for (int c=0;c&lt;mat[i].length;c++){
                System.out.println (&quot;enter grades&quot;);
                mat [i][c] = keyboard.nextDouble();
            }
        }
    }

    public void print () {
        for(int i=0;i&lt;mat.length;i++) {
            for(int c=0;c&lt;mat[i].length;c++) {
                System.out.print(mat[i][c]+&quot; &quot;);
            }
            System.out.println();
        }
    }


    public static void main (String [] args){
        students e = new students();
        e.classroom();
        e.print();

    }
}

答案1

得分: 1

这个函数接受矩阵和行数作为参数,并返回学生平均分列表。每个学生的索引将在返回的列表中维护。

public List<Double> average(double[][] mat, int row_count){
   List<Double> averageList = new ArrayList<>();
   for(int i = 0; i < row_count; i++){
       double averageOfStudent = (mat[i][0] + mat[i][1] + mat[i][2])/3;
       averageList.add(averageOfStudent);
   }
   return averageList;
}
英文:

This function returns the list of student averages given matrix and row_count as arguments. The index of each student will be maintained in the returned list.

public List&lt;Double&gt; average(double[][] mat, int row_count){
   List&lt;Double&gt; averageList = new ArrayList&lt;&gt;();
   for(int i = 0; i &lt; row_count; i++){
       double averageOfStudent = (mat[i][0] + mat[i][1] + mat[i][2])/3;
       averageList.add(averageOfStudent);
   }
   return averageList;
}

答案2

得分: 0

在处理二维数组时,尝试固定其中一个维度,然后处理另一个维度。例如,如果你想要计算一个学生的平均分数!假设他的分数保存在一个名为"grades"的数组中,你可以像下面这样操作:

int sum = 0;
int average = 0;
for (int i = 0; i < grades.length; i++) {
    sum += grades[i];
}
average = sum / grades.length;

现在回到我们的二维数组,你只需要固定一个维度,类似于上面的操作:

int sum = 0;
int average = 0;
for (int i = 0; i < grades.length; i++) { // grades[0][0]将表示第一个学生的第一门课的分数,
                                          // 所以grades[0]x将表示他们的所有分数
    sum += grades[0][i];
}
average = sum / grades.length;

现在,最后,假设你想要对所有学生应用上述操作!可以使用变量和循环,代替0的位置使用一个变量并进行循环:

int[] sum; // 创建一个保存每个学生总分的数组
int[] average; // 创建一个保存每个学生平均分的数组
for (int i = 0; i < grades.length; i++) {
    for (int j = 0; j < grades[0].length; j++) {
        sum[i] += grades[i][j];
    }
    average[i] = sum[i] / grades[0].length;
}

如果要计算每门考试的平均分,与计算每个学生的平均分类似,只是循环的方向不同。

注意:显然你可以同时保存所需的两种平均值(按考试和按学生),但我建议你分别使用两次循环,以保持清晰!

编辑:另一个注意事项:我建议你多了解一下二维数组,因为如果你不真正理解你正在处理的内容,情况可能会变得非常混乱和复杂!

英文:

When working with a 2 Dimensional array try to fix one of the dimensions and work with the other one, for example you want the average grades for ONE student! Let's imagine his grades where saved in 1 array, grades! you'd do something like the following:

int sum=0;
int average=0;
for(int i=0;i&lt;grades.length;i++){
    sum+=grades[i];
}
average = sum/grades.length

So now back to our 2-d array all you need to do is fix one of the dimension to get something similar to what we did above!

int sum=0;
int average=0;
for(int i=0;i&lt;grades.length;i++){ //grades[0][0] will indicate the first grade for 
                                    //the first student, so grades[0]x will represent
                                   // all of their grades basically
    sum+=grades[0][i];
}
average = sum/grades.length

Now finally, say you want to apply the above for all of the students! instead of 0 we can use a variable and loop!

int[] sum// make an array of sum so you get a sum per student
int[] average// make an array of average so you get a average per student
for(int i=0;i&lt;grades.length;i++){
    for(int j=0;j&lt;grades[0].length;j++){
        sum[i]=grades[i][j];
    }
}
average[i] = sum[i]/grades.length

For the average of per exam rather than per student is the same but loop horizontally rather than vertically.

Note: You can obviously save the info you need for both averages (per exams and per student) but I advise you to solve it by looping twice to make it clear!

Edit: Another note: I advise you to read more about 2-d arrays as things can get messy/complicated really fast if you don't actually understand what you're dealing with!

答案3

得分: 0

import java.util.Scanner;

public class Students {
    private static final int NUMBER_OF_EXAMS = 3;

    private Scanner keyboard;
    private double[][] mat;
    private double[] examAverages = new double[NUMBER_OF_EXAMS];
    private double[] studentAverages;

    public void classroom() {
        keyboard = new Scanner(System.in);
        System.out.print("How many students does your classroom have? ");
        int rows = keyboard.nextInt();
        studentAverages = new double[rows];
        mat = new double[rows][NUMBER_OF_EXAMS];
        double[] examTotals = new double[NUMBER_OF_EXAMS];
        double studentTotal = 0.0d;
        for (int i = 0; i < rows; i++) {
            System.out.println("Enter grades for student " + (i + 1));
            studentTotal = 0.0d;
            for (int c = 0; c < mat[i].length; c++) {
                mat[i][c] = getGrade(c);
                studentTotal += mat[i][c];
                examTotals[c] += mat[i][c];
            }
            studentAverages[i] = studentTotal / NUMBER_OF_EXAMS;
        }
        for (int i = 0; i < NUMBER_OF_EXAMS; i++) {
            examAverages[i] = examTotals[i] / rows;
        }
    }

    private double getGrade(int index) {
        if (keyboard.hasNextLine()) {
            keyboard.nextLine();
        }
        System.out.printf("Enter grade %d: ", (index + 1));
        double grade = keyboard.nextDouble();
        return grade;
    }

    public void print() {
        System.out.println("            Exam 1  Exam 2  Exam 3  Average");
        for (int i = 0; i < mat.length; i++) {
            System.out.printf("Student %2d: ", (i + 1));
            for(int c = 0; c < mat[i].length; c++) {
                System.out.printf("%6.2f  ", mat[i][c]);
            }
            System.out.printf("%.2f%n", studentAverages[i]);
        }
        System.out.print("Averages:   ");
        for (int i = 0; i < NUMBER_OF_EXAMS; i++) {
            System.out.printf("%6.2f  ", examAverages[i]);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Students e = new Students();
        e.classroom();
        e.print();
    }
}
英文:

The answer from bleh10 explains the logic, so I won't repeat it here. Nonetheless there are some small details that are either missing or may be misleading which would cause your program not to work as expected, thus leaving you scratching your head as to why.

Firstly, bleh10's answer uses int arrays, when it is clearly stated in your question that grades are double.

Secondly, there are some quirks to be aware of when using Scanner. Refer to this question: Scanner is skipping nextLine() after using next() or nextFoo()?

Finally, I tried to make the below code more "user friendly" by printing appropriate prompts when asking the user to enter values. Also, I changed your print() method so that it displays a table of the results. I presume you may not yet have learned about method printf(), so for an explanation of the formatting strings I used, refer to javadoc for class java.util.Formatter

Here is my complete solution - which started with your original code that I modified. Note that I changed the name of your class according to the Java naming conventions.

import java.util.Scanner;

public class Students {
    private static final int NUMBER_OF_EXAMS = 3;

    private Scanner keyboard;
    private double[][] mat;
    private double[] examAverages = new double[NUMBER_OF_EXAMS];
    private double[] studentAverages;

    public void classroom() {
        keyboard = new Scanner(System.in);
        System.out.print(&quot;How many students does your classroom have? &quot;);
        // We know that 3 exams were done, but not how many students are in the classroom.
        int rows = keyboard.nextInt();
        studentAverages = new double[rows];
        mat = new double[rows][NUMBER_OF_EXAMS];
        double[] examTotals = new double[NUMBER_OF_EXAMS]; // each array element implicitly initialized to zero
        double studentTotal = 0.0d;
        for (int i = 0; i &lt; rows; i++) {
            System.out.println(&quot;Enter grades for student &quot; + (i + 1));
            studentTotal = 0.0d;
            for (int c = 0; c &lt; mat[i].length; c++) {
                mat[i][c] = getGrade(c);
                studentTotal += mat[i][c];
                examTotals[c] += mat[i][c];
            }
            studentAverages[i] = studentTotal / NUMBER_OF_EXAMS;
        }
        for (int i = 0; i &lt; NUMBER_OF_EXAMS; i++) {
            examAverages[i] = examTotals[i] / rows;
        }
    }

    /**
     * Accepts, from user, a single grade for a single exam for a single student.
     * 
     * @param index - exam index
     * 
     * @return Grade entered by user.
     */
    private double getGrade(int index) {
        if (keyboard.hasNextLine()) {
            keyboard.nextLine();
        }
        System.out.printf(&quot;Enter grade %d: &quot;, (index + 1));
        double grade = keyboard.nextDouble();
        return grade;
    }

    /**
     * Displays table of exam results for all students including each student&#39;s average grade
     * plus the average result for each exam.
     */
    public void print () {
        // Print column headers for results table.
        System.out.println(&quot;            Exam 1  Exam 2  Exam 3  Average&quot;);
        for (int i = 0; i &lt; mat.length; i++) {
            System.out.printf(&quot;Student %2d: &quot;, (i + 1));
            for(int c = 0; c &lt; mat[i].length; c++) {
                System.out.printf(&quot;%6.2f  &quot;, mat[i][c]);
            }
            System.out.printf(&quot;%.2f%n&quot;, studentAverages[i]);
        }
        System.out.print(&quot;Averages:   &quot;);
        for (int i = 0; i &lt; NUMBER_OF_EXAMS; i++) {
            System.out.printf(&quot;%6.2f  &quot;, examAverages[i]);
        }
        System.out.println();
    }

    public static void main(String[] args) {
        Students e = new Students();
        e.classroom();
        e.print();
    }
}

Here is the output for a sample run of the above code:

How many students does your classroom have? 2
Enter grades for student 1
Enter grade 1: 70
Enter grade 2: 70
Enter grade 3: 70
Enter grades for student 2
Enter grade 1: 30
Enter grade 2: 30
Enter grade 3: 30
Exam 1  Exam 2  Exam 3  Average
Student  1:  70.00   70.00   70.00  70.00
Student  2:  30.00   30.00   30.00  30.00
Averages:    50.00   50.00   50.00  

huangapple
  • 本文由 发表于 2020年4月10日 11:56:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/61133802.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定