-3
I’m trying to estimate Pi, but I get one NaN
.
var x = 0
var y = 0
var fora = 0
var dentro = 0
var f = document.querySelector('input#t')
var t = Number(f.value)
var pi = document.querySelector('div#pi')
var atual = 0
var distance = 0
function start() {
while (atual < t) {
x = Math.random()
y = Math.random()
distance = x ** 2 + y ** 2
if (distance <= 1) {
dentro += 1
atual += 1
} else {
fora += 1
atual += 1
}
}
pi.innerHTML = 4 * dentro / fora
}
<h1>Calculador de pi</h1>
<p>Insira um número de tentavicas</p><input type="number" name="t" id="t"><input type="button" value="start" onclick="start()">
<div id="pi">asdas</div>
4*dentro/fora
if you never increment the value of "outside" will be a division by zero, pq the variable is started like thisvar fora = 0
, should start with 1, which is a "neutral" value in the– Ricardo Pontual