Java 中的中位数和平方根

Median and square root in Java

我必须实现一个名为“

的静态 public 方法

berechneMittelwertWurzel

”。该方法获取一个双精度数组和两个整数值以及 returns 一个双精度值作为输入参数。 签名:calculateMeanRoot(double[] array, int startindex, int endindex) : double 该方法根据指定范围内的数组中的数字计算平均值(startIndex 到 endIndex)。从平均值计算平方根并返回。

忽略两个指标的负值

有更好的方法吗?

public static double []  berechneMittelwertWurzel(int startindex, int endindex) {
double arr[] = { 5.2, 66.23, -4.2, 0.0, 53.0 };
 double sum = 0;
 for(int i=0; i<arr.length; i++){
    sum = sum + arr[i];
  double average = sum / arr.length;
  
  for(int i =0; i < arr.length;i++)
  {
   for(int j = 0;j < arr.length;j++)
      {
          if(Math.sqrt(arr[i]) == arr[j])
          {
              s += arr[j] + "," + arr[i] + " ";
  if(index < 0 || index >= array.length)
      throw new IndexOutOfBoundsException();

您发布的函数不符合练习中的规范。存在各种问题:

  • 它的论点是错误的
  • 其return类型错误
  • 它不会按照指定检查参数或抛出错误
  • 你的函数似乎创建了一个字符串(分配给一个未声明的变量!),这对解决问题来说是不必要的

此外,你的问题标题提到了中位数;但是,您正在尝试计算算术平均值。从问题文本来看,这实际上可能是正确的。请注意,这两个值通常不同。

要解决此问题,请从以下签名开始并填补空白:

public static double calculateMeanRoot(double[] array, int startindex, int endindex) {
    // if the startIndex > endIndex is an IntervalException should be thrown

    // if the endIndex > array.length -1 or startIndex < 0, the IndexOutOfBoundsException shall be thrown

    // calculate the sum of the array elements between `startIndex` and `endIndex` (*)

    // calculate the mean by dividing the sum by the difference between `endIndex` and `startIndex`

    // if the calculated mean is less than zero (<0), then a NegativeNumberException shall be thrown with an output

    // calculate the square root of the mean, round it, and return it
}

只有注释为(*)的步骤需要循环。