Javascript程序以反向打印数字系列

时间:2011-08-08 23:50:05

标签: algorithm javascript

我不明白为什么下面的JavaScript程序会返回Infinity的答案。我究竟做错了什么?我是新手,非常感谢您的详细解释!

请注意,这只需要使用数学和数学函数,没有字符串函数或数组来完成!

<script type = "text/javascript">

var input;
var rev = 0;

input=window.prompt ("Please enter a 5-digit number to be reversed.");

input = input * 1;

while (input > 0)
{
   rev *= 10;
   rev += input % 10;
   input /= 10;
}
document.write ("Reversed number: " + rev);

</script>

2 个答案:

答案 0 :(得分:4)

您的行:input /= 10;不会产生整数。 你最终会得到一个这样的序列:

input  rev
1234.5 5
123.45 54.5
12.345 548.45

这永远不会命中0,所以你的while条件一直持续到1e-323,然后数字用完精度并变为0。

如果您将input /= 10;行替换为input = Math.floor(input/10);,那么它可以正常工作。

因为这是代码高尔夫,你可能不想使用Math.floor。有一个较小的,我会看到我是否能再找到它。

您可以input = ~~(input/10);使用input始终为正。

答案 1 :(得分:0)

<html>
<head>
<script type="text/javascript">
function reversing(x){
  y=x%10;
  x=parseInt(x/10);
    document.write(y);
     if(x!=0){
      reversing(x);
     }
}
</script>
</head>

<body>
<input id="txt_field" type="text" name="field" />
<input type="button" name="submit" value="Submit" onclick="reversing(document.getElementById('txt_field').value);"/>
</body>
</html>