如何从输入文件中找到均值、中值、众数和范围?

How to find the mean, median, mode, and range from an input file?

我需要从输入文件中找到均值、中值、众数和范围。

[input file has the numbers{60,75,53,49,92,71}]

我不知道如何打印范围外的计算结果或计算众数。

这很糟糕,我是 Java 的新手。

如果有人能帮助我,那就太好了。

import java.io.*;
import java.util.*;

public class grades {

    public static double avg(double[] num) {
        double total = 0;
        int j = 0;
        for (; j < num.length; j++) {
            total += num[j];
        }
        return (total / j);
    }

    public double getRange(double[] numberList) {
        double initMin = numberList[0];
        double initMax = numberList[0];
        for (int i = 1; i <= numberList.length; i++) {
            if (numberList[i] < initMin) initMin = numberList[i];
            if (numberList[i] > initMax) initMax = numberList[i];
            double range = initMax - initMin;

        }
        return range;
    }

    public static void main(String[] args) throws IOException {
        double[] num = new double[12];
        File inFile = new File("data.txt");
        Scanner in = new Scanner(inFile);
        for (int i = 0; i < num.length && in.hasNext(); i++) {
            num[i] = in.nextDouble();
            // System.out.println(num[i]); 
        }

        double avg = grades.avg(num);
        System.out.println("Arithmetic Mean = " + avg);
        System.out.printf("Median = %.2f%n", grades.getMedian(num));
        System.out.println("Range = " + range);


    }

    public static double getMedian(double[] num) {
        int pos = (int) num.length / 2;
        return num[pos];
    } 

}

I don't know how to print the calculations from the range out or calculate the mode.

您已经编写了一个函数来计算范围。以下是打印范围的方法。

System.out.println("Range = " + getRange(num));

这是计算众数的快速代码片段:

public static double calculateMode(final double[] numberList) {
    double[] cnts = new double[numberList.length];
    double mode = 0, max = 0;

    for (int i = 0; i < numberList.length; i++) {
        /* Update Count Counter */
        cnts[numberList[i]]++;
        /* Check */
        if (max < cnts[numberList[i]]) {
            /* Update Max */
            max = cnts[numberList[i]];
            /* Update Mode */
            mode = numberList[i];
        }
    }
    /* Return Result */
    return mode;
}

尝试将元素排序为 array.it 将给出以下结果:

    [49,53,60,71,75,92]

假设你将它存储在数组 A 中。

int arrLength=A.length();
for(i=0,sum=0;i<arrlength;i++)
    sum=sum+A[i]
mean=sum/arrLength;
median=A[arrLength/2]

我认为您在找到中位数之前没有对元素进行排序。 做同样的事情来计算 range.It 会更容易,我觉得