gpt4 book ai didi

java - 如何计算数组的中位数?

转载 作者:IT老高 更新时间:2023-10-28 20:47:23 25 4
gpt4 key购买 nike

我正在尝试计算由文本字段接收的输入填充的数组的总数、平均值和中位数。我已经设法计算出总数和平均值,但我无法让中位数起作用。我认为在执行此操作之前需要对数组进行排序,但我不确定如何执行此操作。是这个问题,还是我没有找到另一个问题?这是我的代码:

import java.applet.Applet;
import java.awt.Graphics;
import java.awt.*;
import java.awt.event.*;

public class whileloopq extends Applet implements ActionListener
{
Label label;
TextField input;
int num;
int index;
int[] numArray = new int[20];
int sum;
int total;
double avg;
int median;



public void init ()
{
label = new Label("Enter numbers");
input = new TextField(5);
add(label);
add(input);
input.addActionListener(this);
index = 0;
}

public void actionPerformed (ActionEvent ev)
{
int num = Integer.parseInt(input.getText());
numArray[index] = num;
index++;
if (index == 20)
input.setEnabled(false);
input.setText("");
sum = 0;
for (int i = 0; i < numArray.length; i++)
{
sum += numArray[i];
}
total = sum;
avg = total / index;

median = numArray[numArray.length/2];



repaint();

}



public void paint (Graphics graf)
{



graf.drawString("Total = " + Integer.toString(total), 25, 85);
graf.drawString("Average = " + Double.toString(avg), 25, 100);
graf.drawString("Median = " + Integer.toString(median), 25, 115);



}
}

最佳答案

Java 中的 Arrays 类有一个静态排序函数,您可以使用 Arrays.sort(numArray) 调用该函数。

Arrays.sort(numArray);
double median;
if (numArray.length % 2 == 0)
median = ((double)numArray[numArray.length/2] + (double)numArray[numArray.length/2 - 1])/2;
else
median = (double) numArray[numArray.length/2];

关于java - 如何计算数组的中位数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955728/

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