我想確定每個用戶提供的輸入是max
或min
他們的所有輸入,然後將該輸入指定給一個變量high
或low
需要幫助確定用戶輸入的最大和最小
int inputnum = 0;
double sum = 0;
double lastinput = 0;
double high;
double low;
double average;
Scanner input = new Scanner(System.in);
high = 0;
low = 0;
do {
System.out.println("Enter a number. Type 0 to quit.");
lastinput = input.nextDouble(); //reads input
sum += lastinput; //add to sum
if (lastinput != 0) {
inputnum += 1; //counts number of inputs (except 0)
}
if (lastinput > high && lastinput != 0) {
high = lastinput;
}
if (lastinput < low && lastinput != 0) {
low = lastinput;
}
average = (sum/inputnum);
} while (lastinput !=0); //repeat unless user inputs 0
的問題是,我不能沒有分配給它的值(例如0)聲明變量。如果用戶輸入3
,5
和7
例如low
值仍然定義爲0
。
如果沒有給出輸入,第二種解決方案也將擺脫第一種解決方案的奇怪行爲(在這種情況下,第一種解決方案將具有「低」>「高」)。 +1 –
是@JiriTousek。但是,這只是一個角落案例,可以照顧程序員也想要的任何方式。它從編碼器到編碼器。 – 97amarnathk