gpt4 book ai didi

java - 如何从输入文件中查找平均值、中位数、众数和极差?

转载 作者:行者123 更新时间:2023-12-02 03:55:36 30 4
gpt4 key购买 nike

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

[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;
}

关于java - 如何从输入文件中查找平均值、中位数、众数和极差?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35499426/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com