2015-10-21 58 views
-3

請幫我弄清楚我的錯誤。當我按照4,5的升序輸入分數時,最小值爲100.我不知道如何改變它?使用Java查找最小和最大值

這裏是我的代碼:

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

回答

0

更改elseelse 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++; 
+0

我剛剛檢查了你的code.its仍然是相同的minimum.no changes.um .. – vini

0

簡化:

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

我覺得你過於複雜的問題:你應該嘗試在邏輯步驟手頭思考的任務:

  1. 讓用戶輸入數字
  2. 添加進入總分的下一個int
  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); 
    } 
}