简体   繁体   中英

Finding Factorial of a number through prompt from the user

I have been struggling with the this output from which hangs my browser. When I run the following code it runs fine.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<script type="text/javascript">
var input = 5;
for(var i=1;i< 5;i++){
input = i*input;
}
document.write(input);
</script>
</body>
</html>

But this hangs the browser and I have to stop it finally. I cant't find any bug or error in this code.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title> 
</head>
<body>
<script type="text/javascript">
    var input = prompt("Enter the number to get factorial of: ");
    var result = input;
    for(var i=1;i < input;i++){
       result = i * result;
    }
    document.write(result);
   </script>
</body>
</html>

input = i*input; increases input so i < input is always false . Try smth like

var input = parseInt(prompt("Enter the number to get factorial of: "));
var result = input;
for(var i=1;i < input;i++){
  result = i * result;
}
document.write(result);
<html>
 <head>
  <title> New Document </title>
  <script type="text/javascript">
 function fact(num)
 {
    var x=parseInt(num);
    if(x>0)
        x=x* fact(x-1);
    alert(x);
 }</script>
 </head>
 <body>
 <form name="f1">
  Enter the Number  :<input type="text" length="8" name="txt1"><br>
  <input type="button" value="Find factiorial" onclick="fact(txt1.value)">
  </form>
 </body>
 var y = prompt("type number ");
var x = input;

 function fact(x) {
   if(x==0) {
      return 1;
   }
   return x * fact(x-1);
}

function run(number) {
    alert(fact(parseInt(number, 10)));
}
run(x);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM