简体   繁体   English

Math.max和Math.min输出允许的最高和最低值

[英]Math.max and Math.min outputting highest and lowest values allowed

so I'm trying to make a program that will output the sum, average, and smallest and largest values. 所以我正在尝试制作一个能输出总和,平均值,最小值和最大值的程序。 I have everything basically figured out except the smallest and largest values are outputting 2147483647 and -2147483647, which I believe are the absolute smallest and largest values that Java will compute. 除了最小和最大值输出2147483647和-2147483647之外,我已经基本找到了所有内容,我认为这是Java将计算的绝对最小值和最大值。 Anyway, I want to compute the numbers that a user enters, so this obviously isn't correct. 无论如何,我想计算用户输入的数字,所以这显然是不正确的。

Here is my class. 这是我的课。 I assume something is going wrong in the addValue method. 我假设addValue方法出了问题。

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

public DataSet()
{
    sum = 0;
    count = 0;
    largest = Integer.MAX_VALUE;
    smallest = Integer.MIN_VALUE;
    average = 0;
}

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

public int getSum()
{
    return sum;
}

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

public int getCount()
{
    return count;
}

public int getLargest()
{
    return largest;
}

public int getSmallest()
{
    return smallest;
}

 }

And here is my tester class for this project: 这是我的测试课程:

 public class DataSetTester {
 public static void main(String[] arg) {
     DataSet ds = new DataSet();
     ds.addValue(13);
     ds.addValue(-2);
     ds.addValue(3);
     ds.addValue(0);
       System.out.println("Count: " + ds.getCount());
       System.out.println("Sum: " + ds.getSum());
       System.out.println("Average: " + ds.getAverage());
     System.out.println("Smallest: " + ds.getSmallest());
       System.out.println("Largest: " + ds.getLargest());
 }
 }

Everything outputs correctly (count, sum, average) except the smallest and largest numbers. 除最小和最大数字外,一切都正确输出(计数,总和,平均值)。 If anyone could point me in the right direction of what I'm doing wrong, that would be great. 如果有人能指出我正在做错的方向,那就太好了。 Thanks. 谢谢。

Reverse your largest & smallest initial values and Math.max & Math.min will select the correct value accordingly: 反转largestsmallest初始值, Math.maxMath.min将相应地选择正确的值:

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

As Integer.MIN_VALUE is the smallest possible value for an integer, the statement: 由于Integer.MIN_VALUE是整数的最小可能值,因此语句:

largest = Math.max(x, largest);

will yield the value x the first time it is called. 将在第一次调用时产生值x

In think you meant in your initialization: 认为你的初始化意味着:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM