JavaScript基础课程减法练习题:生成合规随机数函数需求
JavaScript Subtraction Practice Quiz with Prompt-Based Questions
Got it, let's put together a solution that fits your needs perfectly. I'll break it down into simple, reusable parts so you can tweak it easily if needed.
Step 1: Function to Generate Valid Number Pairs
First, we need a function that spits out two random numbers between 1 and 10, where the first number (minuend) is always larger than the second (subtrahend). A do-while loop is perfect here because it guarantees we'll keep generating numbers until our condition is met.
function generateValidSubtractionPair() { let minuend, subtrahend; // Generate numbers between 1-10 inclusive do { minuend = Math.floor(Math.random() * 10) + 1; subtrahend = Math.floor(Math.random() * 10) + 1; } while (minuend <= subtrahend); // Ensure minuend > subtrahend return [minuend, subtrahend]; }
Step 2: Build the 5-Question Quiz
Next, we'll loop 5 times to create each question. We'll use prompt() to display each subtraction problem, and even include optional answer checking if you want to give feedback to the user.
// Run the 5-question quiz for (let questionNum = 0; questionNum < 5; questionNum++) { // Get our valid number pair const [minuend, subtrahend] = generateValidSubtractionPair(); // Show the question via prompt const userInput = prompt(`Question ${questionNum + 1}: ${minuend} - ${subtrahend} = ?`); // Optional: Uncomment this section to add answer validation /* const correctAnswer = minuend - subtrahend; // Make sure we handle non-numeric input gracefully if (!isNaN(parseInt(userInput)) && parseInt(userInput) === correctAnswer) { alert("Nice work, that's correct!"); } else { alert(`Whoops, that's not right. The correct answer is ${correctAnswer}.`); } */ }
Quick Tips:
- If you want to adjust the number range (say, 1-20 instead of 1-10), just change the
10inMath.random() * 10to your desired upper limit. - The optional answer checking section adds a nice interactive touch, but you can leave it commented out if you only need to display the questions.
内容的提问来源于stack exchange,提问作者Y F
相关产品推荐
相关产品推荐

