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
Just remove
eval
after prompting.The problem is that you’re calling
eval()
when you prompt for the expression. Soexpression
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()
.eval(prompt..
)++
wouldn’t work as expected