我有一個因子查找程序,我已經編程,應該開始檢查輸入框中輸入的值是1還是0,因此它會顯示「因子1是1」。或「0的因子是0」,但是當我在輸入框中輸入數字0時,它顯示「因子爲0」。但我無法弄清楚爲什麼。這可能是一個簡單的錯誤,我無法弄清楚。這是我的代碼。 HTML:功能不顯示正確的結果
<!DOCTYPE HTML>
<html lang="en">
<head>
<title>JavaScript</title>
<script type="text/javascript" src="javaScript/prime.js"></script>
</head>
<body>
<!--Number-->
<h1>Factor finder</h1>
<p>Enter a number to find the factors!</p>
<form name="prime" id="here">
Number:
<input class ="enter2" type="text" name="primeinput" size ="20"/>
<input type="button" name="addnumber" value="Go" onclick="findFactor();"/>
<br />
<h2>Results</h2>
</form>
</body>
</html>
JavaScript的:
//counters
var numbernum = 0;
var numinput = 1;
//function
function findFactor(){
var array = new Array();
//get input
thenumber=document.prime.primeinput.value;
//special circumstances for 1 and 0
if (thenumber == 1 || thenumber == 0){
amount = "The factor of ";
verb = " is ";
} else{
amount = "The factors of ";
verb = " are ";
}
//factor finder
for (i=1; i<thenumber + 1; i++){
//check to see if the number is a factor
if(thenumber % i == 0){
//check if the number is 1 or 0 to state the factors are 1 or 0
//not working with 0
if(thenumber == 1 || thenumber == 0){
if (thenumber == 1){
array[0] = 1;
} else if (thenumber == 0){
array[0] = 0;
}
//if the number isn't 0 or 1
} else if(thenumber != 1 && thenumber != 0){
if (thenumber == numinput){
array[numbernum] = "and " + numinput;
} else{
array[numbernum] = numinput;
numbernum ++
}
}
}
numinput ++
}
//append to the HTML
var make = document.createElement("p");
var apply = document.createTextNode(amount + thenumber + verb + array.join(", ") + ".");
make.appendChild(apply);
document.getElementById("here").appendChild(make);
//reset counters and clear array
numbernum = 0;
numinput = 1;
var array = 0;
}
如果'thenumber'是'0',循環立即終止,因爲'1 <數量寫+ 1'是假的。 – Barmar 2015-02-12 01:29:43
順便說一句,你不需要'else if(then number!= 1 && thenumber!= 0)',只需使用'else'。這與'if'條件相反,'else'只在'if'爲假時才執行。 – Barmar 2015-02-12 01:33:43