范围程序中的Javascript素数不显示结果

时间:2017-05-24 12:42:40

标签: javascript html

我的程序当前没有在其指定的HTML元素中生成任何文本输出。它只说"黄金时间分配:"



var numOne = Number(prompt("Please enter the first whole number to begin the range you'd like to explore."));
var numTwo = Number(prompt("Enter the second whole number to conclude the range you'd like to explore. Hint: Second choice > first."));

if (numOne < numTwo && Number.isInteger(numOne) && Number.isInteger(numTwo)) {
  for (; numOne <= numTwo; numOne++) {
    for (i = 2; numOne <= i; i++) {
      if (numOne % i == 0) {
        break;
      }

      if (numOne == i) {
        document.getElementById("primeTime").innerHTML += numOne + " is a prime number.";
      }
    }
  }
} else {
  window.alert("Please reload the webpage and try again. Error code: User error.");
}
&#13;
<!-- Prime Time Assignment -->
<p id="primeTime"> Prime Time assignment: <br/></p>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

你内心循环的条件是错误的,你需要&gt; = 而你的 if(numOne == i)是错误的地方:

  var numOne = Number(prompt("Please enter the first whole number to begin the range you'd like to explore."));
  var numTwo = Number(prompt("Enter the second whole number to conclude the range you'd like to explore. Hint: Second choice > first."));

  if (numOne < numTwo && Number.isInteger(numOne) && Number.isInteger(numTwo)) {
    for(; numOne <= numTwo; numOne++) {
      for(var i = 2; numOne >= i; i++) {
        if (numOne == i) {
          document.getElementById("primeTime").innerHTML += numOne + " is a prime number.";
        }  

        if (numOne % i == 0) { 
             break;
        }
      }
    }         
  }
  else {
    window.alert("Please reload the webpage and try again. Error code: User error.");
  }