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

时间:2015-10-21 09:37:00

标签: 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 );

3 个答案:

答案 0 :(得分:0)

将您的else更改为else if (score < min),即可获得正确的最低要求。

之所以如此,它检查score是否大于当前max,如果不是这样的话,那么由于其他原因它只是假设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++;

答案 1 :(得分:0)

简化:

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

答案 2 :(得分:0)

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

  1. 让用户输入数字
  2. 添加进入总分的下一个int
  3. 检查下一个int是否为&gt;最后已知的最大值,如果是,则将最后已知的最大值设置为下一个int的值
  4. 否则检查下一个int&lt;最后已知的最小值,如果是,则将最后已知的最小值设置为下一个int的值
  5. 在有更多可用输入的情况下继续
  6. 打印最高分
  7. 计算并打印平均得分(totalScore / amountOfInputs)
  8. 打印最低分
  9. 看起来像这样:

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