我寫了一個javascript,要求用戶輸入5個數字,並檢查最大和最小的數字。我可以讓它顯示最大和最小的數字。主要的問題是,當用戶輸入最多或最多的數字時,我需要顯示一條錯誤消息。當我在前兩個框中輸入兩個大數字時,出現錯誤消息,但如果輸入兩個小數字,則不會收到錯誤消息。這是我的代碼,我懷疑它是我的,但我不完全確定。JavaScript不計算重複正確
編輯:對不起,我忘了提及我只限於使用if-else語句。沒有循環,沒有數組。都不是。我知道,我知道,這絕對是可怕的。
function testProgram() {
var largestNum, smallestNum;
var num1, num2, num3, num4, num5;
var smallDupe, largeDupe;
var num1 = document.getElementById("Num1").value;
var num2 = document.getElementById("Num2").value;
var num3 = document.getElementById("Num3").value;
var num4 = document.getElementById("Num4").value;
var num5 = document.getElementById("Num5").value;
num1 = parseFloat(num1);
num2 = parseFloat(num2);
num3 = parseFloat(num3);
num4 = parseFloat(num4);
num5 = parseFloat(num5);
if ((!isNaN(num1)) && (!isNaN(num2)) && (!isNaN(num3)) && (!isNaN(num4)) && (!isNaN(num5))) {
largestNum = num1;
smallestNum = num1;
smallDupe = 0;
largeDupe = 0;
if(num2 >= largestNum) {
if(num2 == largestNum) {
largeDupe++;
}
else if (num2 <= smallestNum) {
if(num2 == smallestNum) {
smallDupe++;
}
smallestNum = num2;
smallDupe = 0;
} else {
largestNum = num2;
largeDupe = 0;
}
}
if(num3 >= largestNum) {
if(num3 == largestNum) {
largeDupe++;
}
else if (num3 <= smallestNum) {
if(num3 == smallestNum) {
smallDupe++;
}
smallestNum = num3;
smallDupe = 0;
} else {
largestNum = num3;
largeDupe = 0;
}
}
if(num4 >= largestNum) {
if(num4 == largestNum) {
largeDupe++;
}
else if (num4 <= smallestNum) {
if(num4 == smallestNum) {
smallDupe++;
}
smallestNum = num4;
smallDupe = 0;
} else {
largestNum = num4;
largeDupe = 0;
}
}
if(num5 >= largestNum) {
if(num5 == largestNum) {
largeDupe++;
}
else if (num5 <= smallestNum) {
if(num5 == smallestNum) {
smallDupe++;
}
smallestNum = num5;
smallDupe = 0;
} else {
largestNum = num5;
largeDupe = 0;
}
}
if (smallDupe > 0 || largeDupe > 0) {
// Display an error to the user stating that there are duplicates
window.alert("The smallest number and/or largest number contains is duplicated.");
console.log("Error notice");
}
// Reference out1 and out2 to the HTML document
var out1 = document.getElementById("Out1");
var out2 = document.getElementById("Out2");
out1.disabled = false;
out1.value = largestNum;
out2.disabled = false;
out2.value = smallestNum;
} else {
// Tells the user that their input is invalid and to input five numbers again
window.alert("Please input five numbers");
console.log("Error notice");
}
}
請學會使用數組。所有那些重複的代碼都無法關注你在做什麼。 – Barmar 2014-10-01 06:17:36
我不太確定你的意思?道歉,我是一個新手 – user2899245 2014-10-01 06:18:25
如果你把輸入放到一個數組中,對它進行排序,挑選第一個和最後一個作爲最小值和最大值,並且檢查,你可以用所有這些ifs和ifs代替5行代碼如果第二個或倒數第二個值等於最小值和最大值。 – JJJ 2014-10-01 06:18:53