任何人都可以帮我把这个函数写成while循环而不是for循环吗?
function RollAverage(){
//assumes: outputDiv is available for output
//results: counts rolls and averages them
var userNum,countTotal,rollSum;
userNum=parseFloat(document.getElementById('textBox').value);
countTotal=0;
for (rollSum=0; countTotal<userNum; countTotal=countTotal++){
rollSum=rollSum+(RandomInt(1,6) + RandomInt(1,6));
countTotal++;
}
document.getElementById('outputDiv').innerHTML='Heres the average ' +(rollSum/countTotal);
}
答案 0 :(得分:0)
您是否正在使用RandomInt()的任何特定库?我用过了 Math.floor(Math.random(1,6)并修改了while循环的代码,如下所示:
function RollAverage(){
var userNum,countTotal,rollSum;
userNum=parseFloat(document.getElementById('textone').value);
countTotal=0;
rollSum=0;
while (countTotal < userNum){
rollSum = rollSum + (Math.floor(Math.random(1,6) + Math.random(1,6)));
countTotal++;
}
document.getElementById('myDivId').innerHTML =(rollSum/countTotal);
}
此处有完整的jsfiddle代码