java中的中位数和平方根

carvr3hs  于 2021-06-27  发布在  Java
关注(0)|答案(1)|浏览(305)

我必须实现一个名为“的静态公共方法”
berechnemittelwertwurzel公司
”. 该方法获取一个双精度数组和两个整数值作为输入参数,并返回一个双精度值。签名:calculatemeanroot(double[]数组,int startindex,int endindex):double方法从数组中指定范围(startindex到endindex)内的数字计算平均值。根据平均值计算并返回平方根。
两个指标的负值可以忽略不计
如果startindex>endindex是一个intervalexception,则应该抛出它,它继承自RuntimeException。这也应该可以通过消息调用,但是默认构造函数应该保留。
如果endindex>array.length-1或startindex<0,则应抛出indexoutofboundsexception。
如果双数组为空,则返回0。
结果应使用math.round()四舍五入。
如果计算的平均值小于零(<0),则应抛出negativenumberexception并输出。NegativeEnumberException必须从exception继承。输出应该取自exception(没有自己的system.out.println),并包含一个适当的文本,指示平均值和误差。
有更好的方法吗?

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();
798qvoo8

798qvoo81#

您发布的函数不符合练习中的规范。存在各种问题:
它的论点是错误的
其返回类型错误
它不检查参数或抛出指定的错误
您的函数似乎创建了一个字符串(分配给未声明的变量!)这对解决问题是没有必要的
此外,你的问题标题提到了中位数;但是,您正在尝试计算算术平均值。从问题文本来看,这实际上可能是正确的。请注意,这两个值通常是不同的。
要解决这一问题,请从以下签名开始,并填补空白:

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
}

仅步骤注解为 (*) 需要循环。

相关问题