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!
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.");
i开发者_StackOverflow中文版nput = input * 1;
while (input > 0)
{
rev *= 10;
rev += input % 10;
input /= 10;
}
document.write ("Reversed number: " + rev);
</script>
Your line: input /= 10;
doesn't result in an integer.
You end up with a sequence like this:
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.
If you replace the input /= 10;
line with input = Math.floor(input/10);
then it works.
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.
You can use input = ~~(input/10);
provided input
is always positive.
<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>
精彩评论