javascript 反向打印数字系列的Javascript程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6994294/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript program to print a number series in reverse
提问by Snooze
I don't understand why the below JavaScript program returns the answer Infinity. What am I doing wrong? I'm a novice, and would appreciate a detailed explanation!
我不明白为什么下面的 JavaScript 程序返回答案 Infinity。我究竟做错了什么?我是新手,希望得到详细的解释!
Please note that this needs to be accomplished using only math and math functions, no string functions or arrays!
请注意,这需要仅使用数学和数学函数来完成,不要使用字符串函数或数组!
<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>
回答by david
Your line: input /= 10;
doesn't result in an integer.
You end up with a sequence like this:
您的行:input /= 10;
不会产生整数。您最终会得到这样的序列:
input rev
1234.5 5
123.45 54.5
12.345 548.45
This never hits 0, so your while condition just keeps going till it reaches 1e-323, then the number runs out of precision and goes to 0.
这永远不会达到 0,所以你的 while 条件一直持续到它达到 1e-323,然后数字用完精度并变为 0。
If you replace the input /= 10;
line with input = Math.floor(input/10);
then it works.
如果您用 替换该input /= 10;
行,input = Math.floor(input/10);
则它可以工作。
Because this is code golf you probably don't want to use Math.floor though. There is a smaller one, I'll see if I can find it again.
因为这是代码高尔夫,所以您可能不想使用 Math.floor。还有一个小的,我看看能不能再找到。
You can use input = ~~(input/10);
provided input
is always positive.
您可以使用input = ~~(input/10);
提供input
的总是积极的。
回答by Snooze
<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>