如何正确获取数字序列中最大和最小的数字?

时间:2013-10-07 03:26:57

标签: java math

我应该从一系列数字中得到最小和最大的数字。我知道每种方法的方法体可能都不对。有什么帮助吗?

public class DataSet
{
  private int sum;
  private int count;
  private int largest;
  private int smallest;

  public DataSet()
   {
   sum = 0;
   count = 0;
   largest = 0;
   smallest = 0;
   }

 public void addValue(int x)
  {
   sum = sum + x;
   count++;
  }

 public int getSum()
 {
   return sum;
 }

 public double getAverage()
 {
   double average = sum/count;
   return average;
 }

 public int getLargest()
 {
   int largest = Integer.MAX_VALUE;//not giving right answer, don't know how to use
   return largest;
 }

  public int getSmallest()
 {
   int smallest = Integer.MIN_VALUE;//not giving right answer, don't know how to use
   return smallest;
  }
}

如果需要,这是测试人员类,虽然我不认为这里存在问题。

 public class DataSetTester
 {  
   public static void main(String[] args)
    {
    DataSet myData = new DataSet();
    myData.addValue(100);
    myData.addValue(5);
    myData.addValue(4);
    myData.addValue(2);

    System.out.println("Sum = " + myData.getSum());
    System.out.println("Average = " + myData.getAverage());
    System.out.println("Largest value = " + myData.getLargest());
    System.out.println("Smallest value = " + myData.getSmallest());
   }
   }

3 个答案:

答案 0 :(得分:5)

Integer.MAX_VALUEInteger.MIN_VALUE返回Integer值可表示的最大和最小数字

相反,在添加方法时,您需要在添加值时对其进行比较,您可以使用Math.minMath.max来简化比较,例如......

private int smallest = Integer.MAX_VALUE;
private int largest = Integer.MIN_VALUE;

public void addValue(int x)
{
    smallest = Math.min(smallest, x);
    largest = Math.max(largest, x);
    sum = sum + x;
    count++;
}

答案 1 :(得分:0)

这是一个相当容易的任务,你可能只是在想太多。添加值时,必须通过向addValue()添加一些if语句来检查是最小值还是最大值。

    public void addValue(int x)
    {
        sum = sum + x;
        count++;
        if(x > largest)
             largest = x;
        else if(x < smallest)
             smallest = x;
    }

之后,您只需要返回getSmallest和getLargest方法中的最大和最小值。他们应该是这样的:

    public int getLargest()
   {
   return largest;
   }

   public int getSmallest()
   {
   return smallest;
   }

答案 2 :(得分:0)

有几种方法可以做到这一点。一个简单的解决方案是修改addValue()方法:

private int smallest = Integer.MAX_VALUE;
private int largest = Integer.MIN_VALUE;

public void addValue(int x) {
   sum = sum + x;
   count++;
   this.largest = (x > this.largest) ? x : this.largest;
   this.smallest = (x < this.smallest) ? x : this.smallest;
}

此外,您还需要删除这些行:

int largest = Integer.MAX_VALUE;

int smallest = Integer.MIN_VALUE;
来自吸气剂。