我对javascript很陌生,所以请放轻松:)
我试图找出 10 个人选择相同随机数 (1 - 20) 的概率。
当我运行代码时,它每次都会返回相同的答案。在比较数字时,我认为第三个 for 循环有问题。一些帮助将不胜感激,我已经坚持了 3 天了:(
var counter = 0;
//Determine probability (percentage)
for (var i = 1; i <=100; i++) {
//Create array with 10 elements and assign each element with random integer (1 - 20)
for (var j = 1; j <= 10; j++) {
var rndNum = [j];
rndNum = Math.random();
rndNum = Math.floor(rndNum * 20) + 1;
}
//Increment counter if match is found
for (var p1 = 1; p1 <= 9; p1++) {
for (var p2 = p1 + 1; p2 <= 10; p2++) {
if (rndNum[p1] == rndNum[p2]) {
counter++;
}
}
}
}
document.write("The probability of a match is: " + counter + "%");