skip to Main Content

I tried plugging in the expression 1+1/x ,it should have printed the golden ratio 1.618 but it prints out 2.

var num_iterations = 1
var x = 1
const max_iterations = prompt("Max Iterations: ")
var expression = eval(prompt("Expression to be repeatedly calculated: "))
console.log("loading...")
while (num_iterations <= max_iterations) {
  num_iterations++
  x = eval(expression)
}
console.log("The Answer is " + x)

3

Answers


  1. Just remove eval after prompting.

    let num_iterations = 1,
        x = 1;
    
    const
        max_iterations = prompt("Max Iterations: "),
        expression = prompt("Expression to be repeatedly calculated: ");
    
    console.log("loading...");
    
    while (num_iterations <= max_iterations) {
        num_iterations++;
        x = eval(expression);
    }
    
    console.log("The Answer is " + x);
    Login or Signup to reply.
  2. The problem is that you’re calling eval() when you prompt for the expression. So expression doesn’t contain the expression, it contains the result of evaluating it the first time. Then the loop keeps evaluating that result, not the expression.

    Remove that extra call to eval().

    var num_iterations = 1
    var x = 1
    const max_iterations = parseInt(prompt("Max Iterations: "))
    var expression = prompt("Expression to be repeatedly calculated: ")
    console.log("loading...")
    while (num_iterations <= max_iterations) {
      num_iterations++
      x = eval(expression)
    }
    console.log("The Answer is " + x)
    Login or Signup to reply.
    1. You shouldn’t eval the expression twice, remove the first eval (eval(prompt..)
    2. And convert your num_iteration to a number otherwise ++ wouldn’t work as expected
    3. You can make the code shorter my decrimenting max_iteration
    var x = 1
    let max_iterations = +prompt("Max Iterations: ", 10)
    var expression = prompt("Expression to be repeatedly calculated: ", '1+1/x')
    console.log("loading...")
    while (max_iterations--) x = eval(expression)
    console.log("The Answer is " + x)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search