如何在JavaScript中跟踪计算错误

How to trace a computational error in JavaScript

本文关键字:跟踪 计算 错误 JavaScript      更新时间:2023-09-26

我正在开发一个网站,动态创建一个表,并在http://www.primenumbertable.com上为用户突出显示素数。我以为我已经把计算流程正确地绘制出来了,但在我让用户能够包含一个起点之后,有些东西就崩溃了。

不是按照指定的范围计算表,表有时会被截断。例如,如果用户指定要检查100个数字,并且起始点为1,则表将只生成1-9,而不是1-100。

我甚至拿出一支笔和一本便笺簿,试着自己一步一步地计算,看看错误是从哪里来的,但我的笔和便笺簿计算没有计算异常。

在我看来,输入的值在进入表之前以某种方式将最后一个"0"切断,但我找不到这是如何发生的。然后,我想这不可能是问题所在,因为当我试图检查99个数字时,我得到的表格一直到102!

所以,我真的有两个问题:1 -我如何跟踪计算错误的位置,2 -任何人都能看到错误的修复吗?

下面是我的源代码:

<!DOCTYPE HTML>
<html lang="en">
<!-- This page asks the user to input a number to search for primes and returns a base-6 table with primes highlighted -->
<head>
<meta charset="utf-8">
<meta name="keywords" content="prime numbers, prime, primes, prime twins">
<title>Prime Numbers</title>
<script type="text/javascript">
/* This function determines if a number is prime or not */
function isPrime(n) {
 if (isNaN(n) || !isFinite(n) || n%1 || n<2) return false; 
 if (n%2==0) return (n==2);
 if (n%3==0) return (n==3);
 var m=Math.sqrt(n);
 for (var i=5;i<=m;i+=6) {
  if (n%i==0)     return false;
  if (n%(i+2)==0) return false;
 }
 return true;
}
/* This function creates the table and color codes the cells of prime numbers */
function tableCreate(X,Y){
    var numCheck = X;           /* assigns numCheck the value the user input for how many numbers are to be checked*/
    var numRow = numCheck/6;    /* assigns the value that will be used as the number of rows in the table. */
    var numCell = Y;            /* assigns the value that will be used in the table cell */
    var body = document.body;   /* assigns the value of the document body */
    var tbl  = document.createElement('table'); /* creates a table dynamically to be filled */
    var highlightColor = document.getElementById('highlight').value; /* assign the value of the color the user requested for highlighting primes */
    if(isNaN(numCheck)==true){
        document.getElementById('tablearea').innerHTML='Please enter a number in arabic numerals.';
        return; /* if the user did not enter a number to check, the function will instruct the user to do so properly. */
    }
    else{
    for(var i = 0; i < numRow; i++){ /*continues the loop until the proper number of rows have been dynamically filled */
        var tr = tbl.insertRow(-1); /* inserts a new row at the bottom */
        for(var j = 0; j < 6; j++){ /*continues the loop until all data cells in the row have been filled */
            if(i==numRow && j==6 || numCheck==(numCell + Y)-1){
                    break
            } 
            else {
                var td = tr.insertCell(-1); /* inserts a new data cell into the row */
                if(isPrime(numCell) == true){ /* calls the function isPrime to test if the number going into the data cell is a prime */
                    if(highlightColor == ''){
                    td.style.backgroundColor='yellow'; /* uses the color yellow to highlight a cell if the user failed to specify a color */
                    }
                    else{
                    td.style.backgroundColor=highlightColor; /* uses the user's choice of color to highlight the cell if the number going in is prime */
                    }
                }
                td.appendChild(document.createTextNode(numCell)); /* prints the number in the data cell */
                numCell++; /* increases the count of the number of numbers checked by 1 */
            }
        }
    }
    document.getElementById('tablearea').innerHTML='';              /* clears any previous tables that were written */
    document.getElementById('tablearea').appendChild(tbl);          /* writes the new table */
    document.getElementById('backtotop').innerHTML="Back to top";   /* puts a 'back to top' link at the bottom */
    document.getElementById('backtotop').href="#top";               /* links the btt link to the top */
}
}
/* This function clears the tablearea when called */
function tableClear(){
    document.getElementById('tablearea').innerHTML='';
    document.getElementById('backtotop').innerHTML='';
}
</script>
<style type="text/css">
    body{
        background-image: url('primesbackground.png');
    }
    h1{
        width: 700px; 
        margin: auto; 
        text-align: center; 
        background-color: white;
    }
    table{
        width: 50%; 
        border: 1px solid black; 
        background-color: gray; 
        position: relative;
    }
    td{
        border: 1px solid black; 
        background-color: white;
    }   
    .parameters{
        float: left; 
        width: 300px; 
        height: 100%; 
        margin: 10px; 
        display: inline-block;
    }
    .tablearea{
        text-align: center; 
        display: inline-block;
    }
</style>
</head>
<body>
<a id="top"></a>
<h1>Welcome to the Prime Number Table Generator.</h1>
<div>
    <div class="parameters">
        <form name="primes">
        <p style="text-align: center; margin: 10px">
        How many numbers would you like to check for primes?<br />
        <input type="text" id="nums"><br />
        What number would you like to use as a starting point?<br />
        <input type="text" id="startpoint"><br />
        What color would you like primes highlighted?<br />
        <input type="text" id="highlight"><br />
        <input type="button" value="Check'em!" onClick="tableCreate(document.primes.nums.value,document.primes.startpoint.value)">
        <input type="reset" onClick="tableClear()"><br />
        To suggest improvements to this site, please send an email to&nbsp;<a href="mailto:webmaster@primenumbertable.com">webmaster@primenumbertable.com</a>.<br />
        </p>
    </form>
    </div>
    <div id="tablearea" class="tablearea">
    <!-- This area is filled by the function tableCreate() -->
    </div>
    <p style="text-align: center; float: bottom"><a href="" id="backtotop"></a></p>
    </div>
</body>
</html>

Chrome也有开发人员工具(按F12)

似乎是你的numRow属性有问题。

var numRow = numCheck/6;

numCheck为100时,设置numRow为浮点数:16.666666666666668

稍后,您将从for循环中检查break的此值

if(i==numRow && j==6 || numCheck==(numCell + Y)-1){ 

但是i永远不会等于numRow因为i是一个整数而numRow是一个浮点数

我会尝试使用parseInt方法通过替换这行

来解析numCheck为整数
var numRow = numCheck/6;

var numRow = parseInt(numCheck/6);

使用Google Chrome,您可以像这样在JavaScript中插入log: console.log("YOUR LOG");。然后,您可以进入开发人员工具(按F12),选择console选项卡查看日志。

我看了你的代码,主要问题在于你的tableCreate方法中的if条件:

if(i==numRow && j==6 || numCheck==(numCell + Y)-1){
    break
}

Javascript将numCell解释为字符串,因此numCell + Y变成字符串连接。你应该强制Javascript执行整数计算来解决你的问题:

var count = parseInt(numCell) + parseInt(Y) - 1;
if(i==numRow && j==6 || numCheck==count){
    break
}