Java中的平方根和平方根

潘卡伊

我必须实现一个名为“

computeMeanRoot

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

两个指标的负值均应忽略

  • 如果startIndex> endIndex是IntervalException,则应抛出该异常,该继承自RuntimeExeption。这也应该可以通过消息调用,但是默认的构造函数应该保留。
  • 如果endIndex> array.length -1或startIndex <0,则将抛出IndexOutOfBoundsException。
  • 如果double数组为null,则应返回0。
  • 结果应使用Math.round()进行四舍五入。
  • 如果计算的平均值小于零(<0),则将抛出NegativeNumberException与输出。NegativeNumberException必须继承自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();
康拉德·鲁道夫

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

  • 它的论点是错误的
  • 返回类型错误
  • 它不检查参数或抛出指定的错误
  • 您的函数似乎创建了一个字符串(分配给未声明的变量!)对于解决该问题而言是不必要的

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

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

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
}

仅带有注释的步骤(*)需要循环。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章