Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/399.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么HTMLRAND命令会产生超过0.5的结果_Javascript_Html_Random - Fatal编程技术网

Javascript 为什么HTMLRAND命令会产生超过0.5的结果

Javascript 为什么HTMLRAND命令会产生超过0.5的结果,javascript,html,random,Javascript,Html,Random,我编写代码是为了理解html是如何工作的,但我无法完全理解Math.random()函数 <!DOCTYPE html> <html> <body> Value:<br> <p id="Value"> 0 </p> <div> </div> <p>Click the button to increase the value.</p> <button onclick=

我编写代码是为了理解html是如何工作的,但我无法完全理解
Math.random()
函数

<!DOCTYPE html>
<html>
<body>

Value:<br> <p id="Value"> 0 </p>
<div>
</div>

<p>Click the button to increase the value.</p>

<button onclick="increase()"+",this.blur()" id="demp" style="position:relative; left: 500px; top: 80px; width: 64px; height: 64px;">Increase</button>

<script>
function increase() {
    var x = document.getElementById("Value").innerHTML;
    var increased = parseInt(x,10) + parseInt(1,10);
    document.getElementById("Value").innerHTML = increased;
}

function change(){
    var num = 0;
    window.setInterval(function(){
    var speedx= Math.floor((Math.random() * 10) - 5);
    var speedy= Math.floor((Math.random() * 10) - 5);
    document.getElementById("demp").style.left= parseInt(document.getElementById("demp").style.left, 10) + parseInt(speedx,10) +"px"; 
    document.getElementById("demp").style.top= parseInt(document.getElementById("demp").style.top, 10) + parseInt(speedy,10) +"px"; 
    }, 10)
}
window.onload = function start() {
    change();
}
</script>
</body>
</html>

值:

0

单击按钮以增加值

增加 功能增加(){ var x=document.getElementById(“值”).innerHTML; var增加=parseInt(x,10)+parseInt(1,10); document.getElementById(“值”).innerHTML=增加; } 函数更改(){ var num=0; setInterval(函数(){ var speedx=数学地板((数学随机()*10)-5); var=数学地板((数学随机()*10)-5); document.getElementById(“demp”).style.left=parseInt(document.getElementById(“demp”).style.left,10)+parseInt(speedx,10)+“px”; document.getElementById(“demp”).style.top=parseInt(document.getElementById(“demp”).style.top,10)+parseInt(speedy,10)+“px”; }, 10) } window.onload=函数开始(){ 改变(); }
我创建了一个按钮,该按钮根据
Math.random()
value更改其位置。我刷新页面30次,我的按钮总是向上向左移动。这意味着
math.random()
函数产生的值大于0.5
你能解释一下为什么它不能产生真正的随机数,我怎样才能产生真正的随机数

这只是偏见
Math.floor((Math.random()*10)-5)
选择介于-5和4之间的值,因此结果更可能是负值而不是正值。试着用11来代替。因为是负5,
Math.random()*10
是一个浮点数,比如说
3.171433220370915
然后数学地板将它四舍五入,所以现在是3,然后去掉5,所以现在是-2。style left-2和style top-2将其向上和向左移动,按钮的单击处理程序中有一些奇怪的东西:
onclick=“crease()”+,this.blur()
故意的?事实上,你有60%的几率
而40%的几率
你的按钮不会按下
并且
正确。
@Teemu我这样做是因为我不想按下按钮时按钮被涂上颜色,但我不能。我应该删除这个代码。