You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 10 in Math.random() * 10 to 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:39:39