繁体   English   中英

使用 Java 查找最小值和最大值

[英]Finding min and max using Java

请帮助我找出我的错误。 当我按升序输入分数时,如 4,5,最小值为 100。我不知道如何更改它?

这是我的代码:

   float score=0,min=100,max=0,sum1=0,count=0,sum2=0;
    float average,sd;
    Scanner a=new Scanner(System.in);

    while(score>=0)

    {
        System.out.println("enter the score(a negative score to quit)");
        score=a.nextInt();
      if(score<0)

         break;  

         if(score>=max){   
     max=score;
     sum1+=max;  



   }

      else 
     {
     min=score;
     sum2+=min;                         

     }


      count++;
             } 

      average=(sum1+sum2)/(count++ );

    System.out.println("the average : " + average);
    System.out.println( "the maximum score: "+ max);


    System.out.println("the min score: "+ min );

将您的else更改为else if (score < min)并且您获得了正确的最小值。

原因是,它检查score是否大于当前max ,如果不是这种情况,那么它只是假设,由于 else,该score是新的min

if (score >= max) {
    max = score;
}
else if (score < min){
    min = score;
} 
// Just add the score value to the sum, it doesn´t matter if it´s min or max
sum2 += score;
count++;

简化:

while((score = a.nextInt()) >= 0) {
    min = Math.min(min, score);
    max = Math.max(max, score);
    sum += score;
    average = sum / count++;
}

我认为你把问题复杂化了:你应该尝试按逻辑步骤思考手头的任务:

  1. 让用户输入数字
  2. 添加进入总分的下一个整数
  3. 检查下一个 int 是否 > 最后一个已知最大值,如果是,则将最后一个已知最大值设置为下一个 int 的值
  4. 否则检查下一个 int < 上一个已知的最小值,如果是,则将上一个已知的最小值设置为下一个 int 的值
  5. 在有更多可用输入时继续
  6. 打印最高分
  7. 计算并打印平均分(totalScore / amountOfInputs)
  8. 打印最低分数

看起来像这样:

import java.util.*;

public class MaxMinAverage {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        double score, currentMinimum = Integer.MAX_VALUE, currentMaximum = Integer.MIN_VALUE, count;
        while (in.hasNextInt()) {
            int nextInt = in.nextInt();
            if (nextInt < 0) { //break out of the loop
                break;
            } else {
                score += nextInt;
                count++;
                if (nextInt > currentMaximum) {
                    currentMaximum = nextInt;
                } else if (nextInt < currentMinimum) {
                    currentMinimum = nextInt;
                }
            }
        }
        System.out.println("Max: " + currentMaximum);
        System.out.println("Avg: " + (score / count));
        System.out.println("Min: " + currentMinimum);
    }
}

暂无
暂无

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

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