【问题标题】:Median and square root in JavaJava中的中位数和平方根
【发布时间】:2021-04-10 08:13:19
【问题描述】:

我必须实现一个名为“

的静态公共方法

berechneMittelwertWurzel

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

两个索引的负值都可以忽略

  • 如果 startIndex > endIndex 是 IntervalException,则应抛出 IntervalException,它继承自 RuntimeExeption。这也应该可以通过消息调用,但应该保留默认构造函数。
  • 如果 endIndex > array.length -1 或 startIndex
  • 如果双精度数组为空,则返回0。
  • 结果应使用 Math.round() 进行四舍五入。
  • 如果计算的平均值小于零 (

有没有更好的方法?

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

【问题讨论】:

  • 好吧,如果可能的话,我将从按顺序实施项目符号开始。这意味着首先检查索引并在需要时抛出异常,然后如果数组为空或为空则返回 0,最后进行计算。除此之外,您的任务已经提供了一个方法签名:double calculateMeanRoot(double[] array, int startindex, int endindex)。你为什么不用它?
  • 如果double数组为null,则返回0是什么意思?
  • "有更好的方法吗?" - 简而言之:是的。为什么?因为你的计算是错误的。我不确定这些内部循环的用途,但您基本上应该执行以下操作:1)计算指定范围内所有元素的总和(即在索引start, start + 1, ... ,end),2a)如果总和为负,则抛出一个例外或 2b) 如果总和 >= 0,则使用该范围的长度计算平均值(长度可以从索引中计算出来)和 3) 从该平均值计算平方根。
  • 最后一条评论:"mean value""median" 是不同的东西。由于您在问题中使用了德语:mean value = Mittelwert(最常见的是平均值),median = Median(系列中的中心/中间值)
  • @Thomas 事实上,“Mittelwert”和“average”都是相当非正式的术语,可以指代不同的值,偶尔也可以指中位数和平均值。但令人困惑的是,它们也可以用来专门指代平均值而不是中位数。最好在重要的地方完全避免它们。

标签: java median negative-number


【解决方案1】:

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

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

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

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

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
}

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

【讨论】:

  • 我想添加一个更正(基于我从问题中理解的内容):而不是计算整个数组的总和和平均值,它似乎只是两个索引之间的范围/子数组应该计算。代码 cmets 3 和 4 应该反映这一点。
猜你喜欢
  • 2015-12-28
  • 1970-01-01
  • 1970-01-01
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2015-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多