Home > OS >  Random number generation node.js
Random number generation node.js

Time:06-23

I have been trying to run a readline module (using node.js on Visual studio code) that will allow me to generate two random numbers between one and ten and ask the user what the answer is if they were to add the two together. I am having trouble accessing the random numbers when asking the question, I have given my attempt at the random number generation and the question, any help greatly appreciated.

let num1 = Math.floor((Math.random() * 10)   1); 
let num2 = Math.floor((Math.random() * 10)   1);

rl.question('What is ${num1}   ${num2}?' , (userInput) => {
    console.log(userInput); 
}); 

When running this in the terminal I get this:

What is ${num1}   ${num2}?

Then if I put in any input (for example bananas) I get that input back as an answer.

CodePudding user response:

I'd suggest trying the following code, I'm using the ` operator to allow string interpolation:

let num1 = Math.floor((Math.random() * 10)   1); 
let num2 = Math.floor((Math.random() * 10)   1);

rl.question(`What is ${num1}   ${num2}?` , (userInput) => {
    console.log(userInput);
    console.log('Your answer is:', ((num1   num2) ===  userInput) ? 'correct': 'incorrect');
    rl.close();
});
  • Related