Java 需要帮助确定用户输入的最大值和最小值吗

Java 需要帮助确定用户输入的最大值和最小值吗,java,max,min,Java,Max,Min,我试图确定用户提供的每个输入是否是其所有输入中的max或min,然后将该输入分配给变量high或low int inputnum = 0; double sum = 0; double lastinput = 0; double high; double low; double average; Scanner input = new Scanner(System.in); high = 0; low = 0; do { S

我试图确定用户提供的每个输入是否是其所有输入中的
max
min
,然后将该输入分配给变量
high
low

int inputnum = 0;
    double sum = 0;
    double lastinput = 0;
    double high;
    double low;
    double average;
    Scanner input = new Scanner(System.in);
    high = 0;
    low = 0;
do {
    System.out.println("Enter a number. Type 0 to quit.");
    lastinput = input.nextDouble(); //reads input
    sum += lastinput; //add to sum
    if (lastinput != 0) {
        inputnum += 1; //counts number of inputs (except 0)
    }
    if (lastinput > high && lastinput != 0) {
        high = lastinput;
    }
    if (lastinput < low && lastinput != 0) {
        low = lastinput;
    }

    average = (sum / inputnum);

} while (lastinput !=0); //repeat unless user inputs 0
double low = Double.MAX_VALUE;
int inputnum=0;
双和=0;
双输入=0;
双高;
双低;
双倍平均;
扫描仪输入=新扫描仪(System.in);
高=0;
低=0;
做{
System.out.println(“输入一个数字,键入0退出”);
lastinput=input.nextDouble();//读取输入
sum+=lastinput;//添加到sum
如果(lastinput!=0){
inputnum+=1;//统计输入数(0除外)
}
如果(lastinput>high&&lastinput!=0){
高=最后的输入;
}
如果(lastinput

问题是我不能在不给变量赋值的情况下声明它(例如0)。例如,如果用户输入
3
5
7
,则
low
值仍然定义为
0
,这是因为您将
low
初始化为零,并且输入的所有值都较大,因此它永远不会更新。您必须将其分配给可能的最高值-
low=Double.MAX\u值因此所有其他值都将低于它

类似地,您应该将high初始化为

high = Double.MIN_VALUE;

默认情况下,应为
low
使用最大值,否则非负输入的条件
lastinput
将始终为
false
,0保留为输出

double low = Double.MAX_VALUE;

问题在于您的以下状况:

if (lastinput < low && lastinput != 0) {
    low = lastinput;
}
  • 更改if条件:您可以更改
    if
    条件,以说明初始值为0的事实

    if (low==0 || (lastinput < low && lastinput != 0)) {
        low = lastinput;
    }
    
    if(low==0 | |(lastinput

  • low
    high
    的值可以通过循环之前的第一次输入进行初始化。

    double
    它是:)对于几个测试用例,这完全符合我的预期。但是,当我输入'-1'、'-2'、'-3'然后输入'0'时,我的最小值显示为'4.9E-324'。这是什么原因造成的?很奇怪,我得到0。您使用的是哪个IDE?如果没有输入,第二个解决方案也将消除第一个解决方案的奇怪行为(在这种情况下,第一个解决方案将具有
    low>
    high`)+1是@JiriTousek。但这只是一个小问题,程序员也可以用任何方式处理。这取决于不同的编码者。