2013-09-21 234 views
-1

大家好,我的代碼應該做到下面這條指令,但我沒有得到它在所有Java輸入和輸出把

用戶可以根據需要在控制檯上輸入的許多積極的浮點數。零(或一個負數)表示輸入結束(不能輸入更多數字)。輸入後 顯示 數最少的程序輸入(分鐘) 數量最多輸入(最大值) 所有數字的平均值進入(平均) 不要用數組這個任務,即使你知道他們。

樣品應該是這樣的

輸入號碼:\ n輸入 1 2 3 4 5 6 0 \ n 編號:6 \ n 最小:1.00 \ n 最大:6.00 \ n 平均值:3.50 \ n

輸入數字:\ n 0 \ n 未輸入數字。

public class LoopStatistics { 

public static void main(String[] args) { 

    double max, min, sum=0, input, mean=0; 
    int counter = 0; 

    TextIO.putln("enter numbers:"); 

    do 
    { 
     input = TextIO.getDouble(); 

     min = input; 
     max = input; 

     counter++; 

     if (input > max) 
      max = input; 

     if (input < min) 
      min = input; 

     sum = sum + input; 



     } while(input != 0); 
    mean = sum/counter; 
    TextIO.putf("numbers entered:%d\n", counter); 
    TextIO.putf("minimum:%f\n", min); 
    TextIO.putf("maximum:%f\n", max); 
    TextIO.putf("mean:%f", mean); 





} 

} 

回答

1

您將其分配maxmin你測試之前,他們是否比當前max/min大於/小於:

min = input; 
max = input; 

這意味着,他們都等於不管最後輸入的人。

整理你的代碼和刪除這些調用率:

public static void main(String[] args) throws Exception { 
    final Scanner scanner = new Scanner(System.in); 
    double max = 0; 
    double min = Double.POSITIVE_INFINITY; 
    double sum = 0; 
    int counter = 0; 
    while (true) { 
     final double d = scanner.nextDouble(); 
     if (d <= 0) { 
      break; 
     } 
     sum += d; 
     max = Math.max(max, d); 
     min = Math.min(min, d); 
     ++counter; 
    } 
    System.out.println("Max=" + max); 
    System.out.println("Min=" + min); 
    System.out.println("Ave=" + sum/counter); 
} 
+0

你能不能給我的建議,使這項工作? –

+0

對不起,問題太多了,但Double.POSITIVE_INFINITY;做什麼? –

+0

@邁克爾你認爲它有什麼作用?你有沒有聽說過這個谷歌的東西?你可以查看[javadocs](http://docs.oracle.com/javase/7/docs/api/java/lang/Double.html#POSITIVE_INFINITY)。 –