gpt4 book ai didi

java - 我的 "find median"实现中有什么错误?

转载 作者:行者123 更新时间:2023-12-02 04:44:33 24 4
gpt4 key购买 nike

我发现有人有类似的问题( How to calculate the median of an array? ),但我不知道如何将其合并到我自己的代码中,因为我对 java 相当陌生。现在,我的 findmedian 方法返回 0 而不是实际的中位数,我似乎无法弄清楚。谢谢!

import java.util.Scanner;
import java.util.Arrays;

public class Original
{
public static void main(String[] args)
{
Scanner inputNumber = new Scanner(System.in);
Scanner dataItem = new Scanner(System.in);
Scanner input = new Scanner(System.in);

System.out.print("This stores a list of contirbutions to a charity drive.\n ");
System.out.print("How many contributors will be entered? ");

double contributors = inputNumber.nextDouble();
double contributions[ ] = new double[50];
double contributions_check[] = findData (contributors, contributions);

System.out.print("See if the contributions are correct. ");

// Displays the contributions, loop allows numbers to be displayed correctly
for (int count = 0; count < contributors; count++) {
System.out.print(contributions_check[count] + " ");
}

double median = findmedian(contributors,contributions_check);
System.out.print("\n The median contribution is: " + median);
}

public static double[] findData(double n, double[] contributions2)
{
Scanner dataItem = new Scanner(System.in);

// x must be 0 and x must be < than n
for (int x = 0; x < n; x++) {
System.out.print("Please enter the next contribution: ");
contributions2[x] = dataItem.nextDouble();
}

return contributions2;
}

public static double findmedian(double n, double data[])
{
Arrays.sort(data);
double median;

if (data.length % 2 == 0) {
median = ((double) data[data.length / 2] +
(double) data[data.length / 2 - 1]) / 2;
} else {
median = (double) data[data.length/2];
}

return median;
}
}

最佳答案

我认为问题是您在 findmedian 中使用 data.length,而您应该在其中使用 ndata.length 始终为 50,即使您只输入了 5 个项目......

关于java - 我的 "find median"实现中有什么错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29776094/

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