1

I want to Pick a random number from the range (100,200) {inclusive} . Why is it adding in between the range.

// This will return a Random Number from Given Range

function randomNumberGeneratorInRange(rangeStart, rangeEnd) {
  return Math.random() * rangeEnd + rangeStart;
}
console.log(`My random number: ${randomNumberGeneratorInRange(10, 50)}`);
console.log(`My random number: ${randomNumberGeneratorInRange(100, 200)}`);

enter image description here

Prem Kumar
  • 11
  • 2
  • 1
    `Math.random() * rangeEnd` should be `Math.random() * (rangeEnd - rangeStart)` – Barmar Nov 12 '21 at 16:21
  • Because `Math.random() * rangeEnd` gives you between `0` and the maximum. If the maximum is `200` and the random number is `180`, you still add the minimum to it making it `280` – VLAZ Nov 12 '21 at 16:23
  • [Random Number Generation in Javascript going outside of range](https://stackoverflow.com/q/41942778) – VLAZ Nov 12 '21 at 16:24
  • But this way, it will pick number in difference only. Like (200-100) >> this will not exceed 100 right?? – Prem Kumar Nov 12 '21 at 16:26
  • Replying to VLAZ >> I am adding rangeStart at the end.. this is the full code Math.random() * rangeEnd + rangeStart; – Prem Kumar Nov 12 '21 at 16:28
  • I think this is the correct code : Math.random() * (rangeEnd - rangeStart) + rangeStart; – Prem Kumar Nov 12 '21 at 16:30

0 Answers0