Home >Web Front-end >JS Tutorial >How to generate two random numbers in javascript

How to generate two random numbers in javascript

醉折花枝作酒筹
醉折花枝作酒筹Original
2021-06-09 11:31:403426browse

Method to generate random numbers: First use the "random()" method to return a random number between 0 and 1, and then multiply the obtained random number by the specified number plus the specified number to obtain Random numbers within the specified range; finally use the "floor()" method to return the largest integer less than or equal to the specified interval.

How to generate two random numbers in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Use Math.floor() in combination with Math.random().

This simple line of code will return you a number between 1 and 6 (all inclusive):

Math.floor(Math.random() * 6 + 1)

There are 6 possible results here: 1, 2, 3, 4 ,5,6.

Extended information:

The random() method can return a random number between 0 ~ 1.

<html>
<body>

<script type="text/javascript">

document.write(Math.random())  //一个可能结果:0.3564017841844467

</script>

</body>
</html>

The floor() method returns the largest integer less than or equal to x. If the passed parameter is an integer, the value is unchanged.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>document</title>
</head>
<body>

<p id="demo">单击按钮将不同的数值降到离它最近的整数。</p>
<button onclick="myFunction()">点我</button>
<script>
function myFunction(){
	var a=Math.floor(0.60);
	var b=Math.floor(0.40);
	var c=Math.floor(5);
	var d=Math.floor(5.1);
	var e=Math.floor(-5.1);
	var f=Math.floor(-5.9);
	var x=document.getElementById("demo");
	x.innerHTML=a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>" + f; 
}
</script>

</body>
</html>

How to generate two random numbers in javascript

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of How to generate two random numbers in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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