Home > Web Front-end > JS Tutorial > How to output random integers from m to n in js

How to output random integers from m to n in js

下次还敢
Release: 2024-05-01 03:57:13
Original
635 people have browsed it

In JavaScript, you can use the following steps to generate a random integer between m and n: Use Math.random() to generate a random number between 0 and 1. Multiply the result by the range (n - m 1). Round the result to an integer. Add m to the result.

How to output random integers from m to n in js

How to output a random integer between m and n in JavaScript

In JavaScript, we can use Math.random() function and range operators (...) to generate random integers between m and n.

Steps:

  1. Use the Math.random() function to generate a random number between 0 and 1.
  2. Multiply the result by the range (n - m 1).
  3. Use the rounding operator (Math.floor()) to round the result to an integer.
  4. Add m to the result to get a random integer between m and n.

Code example:

<code class="javascript">function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}</code>
Copy after login

Usage:

<code class="javascript">const randomNumber = getRandomInt(5, 10); // 输出 5 到 10 之间的随机整数
console.log(randomNumber); // 例如,输出 8</code>
Copy after login

The above is the detailed content of How to output random integers from m to n in js. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template