2016-12-10 38 views
-3

如果輸入96以下的數字比0應該出現,應該出現96和192 3之間,並且如果輸入等於或大於192,輸出應該是6.但是在我的出於某種原因代碼,情況並非如此,輸入0和1返回0,輸入返回2-99 6,100通過191返回0,和192及以上的返回6大於不給出正確的讀數

這裏是代碼

var number = document.getElementById("width").value; 
var text; 


if (number >= "192") { 
    text = "6"; 


} else if (number >= "96") { 
    text = "3"; 

} else { 
    text = "0"; 
} 
document.getElementById("smallquantity").innerHTML = text; 
+1

用戶輸入'#width'是什麼?它會是一個數字還是一個字母? – BenM

+3

請澄清您的具體問題或添加其他詳細信息,以突出顯示您的需要。正如目前所寫,很難確切地說出你在問什麼。 –

+1

你知道字符串比較是如何工作的嗎?看看[這個問題](http:// stackoverflow。COM /問題/ 10863092 /爲什麼 - 是串-11-低於串-3)。字符串'「192」'和'「c」'不是一回事。 –

回答

0

字符串被lexigraphically相比,上市的事情「按字母」含義時,基於字符的順序;比較碰巧包含數字的兩個字符串與比較兩個數字不同。

"2" > "1294"因爲性格2而來的字符1後。

只需改變你的邏輯使用數字。首先,解析HTML元素的內容。下面的10意味着使用基地10解釋數量時(很重要,因爲像"012"被解釋爲一個八進制數,不是小數):

var letter = parseInt(document.getElementById("width").value, 10); 

...然後改變你的比較,使用數字,而不是字符串:

if (letter >= 192) 
0

嘗試比較字符串

var letter = document.getElementById("width").value; 
var text; 

// If the letter is "c" 
if (letter.localeCompare("c")) { 
    text = "6"; 

// If the letter is "e" 
} else if (letter.localeCompare("e")) { 
    text = "3"; 

// If the letter is anything else 
} else { 
    text = "0"; 
} 
document.getElementById("smallquantity").innerHTML = text; 
0

我認爲你已經嘗試了你的邏輯錯誤的方式。 嘗試以下

if(letter < "96") 
    text = "0"; 
else if (letter < "192") 
    text = "3"; 
else 
    text = "6"; 

我認爲它會給你正在尋找的輸出。 但我強烈建議你解析輸入,然後在數字比較的if塊中使用它。

var letter = parseInt(document.getElementById("width").value); 
if(letter < 96) 
    text = "0"; 
else if (letter < 192) 
    text = "3"; 
else 
    text = "6"; 
+0

我認爲他的整個方法是錯誤的。 'letter <「192」'在這麼多層次上是不正確的。 –

+0

可能是。但我們不能確定,因爲我們不知道他的輸入是什麼。從他的描述我得到他得到輸出,但不正確,因爲他在錯誤的邏輯設計,如果塊。 – reza

+0

他也說*用戶將在最後的評論中輸入一個數字,而不是一個字母* – reza

0

要與ASCII值進行比較,首先需要convert it to ASCII。你不能馬上比較。
另外,字母「c」有ASCII值99,而不是192.
您應該先轉換爲ASCII,然後與正確的值(數值,而不是數字作爲字符串)進行比較。
也是你的邏輯錯誤 - 如果是「c」 - > ELSE是「c」或「e」。你永遠不會在ELSE中得到那個「c」。

var letter = document.getElementById("width").value.charCodeAt(0); 
var text; 

// If the letter is "c" 
if (letter == 99) { 
    text = "6"; 

// If the letter "e" 
} else if (letter == 101) { 
    text = "3"; 

// If the letter is anything else 
} else { 
    text = "0"; 
} 
document.getElementById("smallquantity").innerHTML = text; 

現在你明白了這個想法。您可以相應地調整IF。

0

從@jacob和@reza獲得幫助後,我提出瞭解決我的問題的代碼。感謝所有幫助我解決問題的人!

var number = parseInt(document.getElementById("width").value, 10); 
    var text; 
    if (number < "96") { 
    text = parseFloat(0); 

    } else if (number < "192") { 
    text = parseFloat(3); 

    } else { 
    text = parseFloat(6); 
    } 
    document.getElementById("largequantity").innerHTML = parseFloat(text) * parseFloat(quantity);