javascript - Why is my JS random ints generator so wrong when I give him one negative and one positive number? -
so use such script random int generation inside of range
function randominrange(start, end) { if ((start >= 0) && (end >= 0)) { return math.round(math.abs(start) + (math.random() * (math.abs(end) - math.abs(start)))); } else if ((start <= 0) && (end <= 0)) { return 0 - (math.round(math.abs(start) + (math.random() * (math.abs(end) - math.abs(start))))); } else { return math.round(((start) + math.random() * (end - start))); } }
you can see @ work here. positive ranges correct, negative correct bad , wrong results mixed. why , how fix it?
i try use formula math.round(start + math.random() * (end - start));
ok, found problem, you're performing algebra on strings (since in code $('fnt').value
value of input box, string), not numbers, things +
end concatenating strings , not adding numeric content. in particular example, have:
math.round(((start) + math.random() * (end - start)))
which evaluates to:
math.round((('13') + math.random() * ('-666' - '13')))
which evaluates (for example):
math.round("13-339.44615370430984")
since '13' + '-339.44615370430984'
concatenated, , math.round
call return nan
you should have:
function randominrange(start, end) { start = number(start); end = number(end); return math.round(start + math.random() * (end - start)); }
or change values pass function, making sure they're numbers.
Comments
Post a Comment