[英]How to find the lowest number in an input loop?
我必須編寫一個代碼,告訴用戶輸入4個數字(它們可以是十進制),並打印這些數字的平均值和最小值。
到目前為止,我已經設法獲得了平均值,但是我很難獲得最低的數字。
int iteration = 0;
float number;
float total = 0;
float average;
float lowest;
Scanner input = new Scanner(System.in);
while (iteration < 4){
System.out.println("Enter score : ");
number = input.nextFloat();
iteration++;
total += number;
}
average = total / 4;
System.out.println("The average is: " + average);
您可以使用值Float.MAX_VALUE
來初始化lowest
值,每當用戶輸入一個值時, Float.MAX_VALUE
lowest
值與輸入值進行比較,並將新的較小值分配給最低值。
int iteration = 0;
float number;
float total = 0;
float average;
float lowest = Float.MAX_VALUE;
Scanner input = new Scanner(System.in);
while (iteration < 4){
System.out.println("Enter score : ");
number = input.nextFloat();
iteration++;
total += number;
if(number < lowest){
lowest = number;
}
}
average = total / 4;
System.out.println("The average is: " + average);
System.out.println("The minimum is: " + lowest);
嘗試這個:
float minValue = Double.MAX_VALUE;
while(...){
...
number = input.nextFloat();
minValue = Math.min(minValue, number);
...
}
希望這個能對您有所幫助:)。
最初定義float lowest = some big no
。 現在,每次輸入時,請與lowest
輸入進行比較。 如果輸入小於lowest
將其指定為lowest
,否則不改變lowest
。
就像Olli Zi所說的那樣,您可以通過使用簡單的函數Math.min()來獲得最小值。此外,為了進一步理解,我也提供了代碼。
int iteration = 0;
float number[]=new float[4];
float total = 0;
float average;
float lowest;
Scanner input = new Scanner(System.in);
while (iteration < 4){
System.out.println("Enter score : ");
number[iteration] = input.nextFloat();
total += number[iteration];
iteration=iteration+1;
}
average = total / 4;
System.out.println("The average is: " + average);
System.out.println(Math.min(Math.min(number[0],number[1]), Math.min(number[2],number[3])));
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.