我有一个我编程的因子查找器应该通过检查输入框中输入的值是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;
}
答案 0 :(得分:0)
因为这个而没有循环:
for(i = 1; i&lt; 0 + 1
尝试将其更改为
for(i = 1; i&lt; = thenumber
答案 1 :(得分:0)
在0
和1
的特殊情况下,请不要理会for
循环,因为您知道正确的结果应该是什么。所以将if
放在for
:
if (thenumber < 2) {
array[0] = thenumber;
} else {
for (var i = 1; i <= thenumber; i++) {
if (thenumber % i == 0) {
array.push(i);
}
}
}