我正在尝试编写一个非常简单的JS程序。我希望它生成1到100之间的10个随机数,并显示它们中有多少是偶数,有多少是奇数。我一直在寻找,我无法找到为什么这不起作用。无论组合如何,它都会显示0个偶数和10个奇数。我在俯瞰什么?
function main()
{
var number = 0;
var totalNumbers = 0;
var evenNumbers = 0;
var oddNumbers = 0;
document.write("Here are ten random numbers between 1 and 100:<br><br>");
while(totalNumbers < 10)
{
number = document.write((Math.floor((Math.random()* 100)+1)) + "<br>");
if(number % 2 == 0)
{
evenNumbers++;
}
else
{
oddNumbers++;
}
totalNumbers++;
}
document.write("<br><br>Even Numbers: " + evenNumbers + "<br>" +
"Odd Numbers: " + oddNumbers);
}
答案 0 :(得分:10)
document.write()
不会返回数字。在调用document.write()
之前将数字存储在变量中。
while(totalNumbers < 10)
{
var number = Math.floor((Math.random()* 100)+1;
document.write(number + "<br>");
if(number % 2 == 0)
{
evenNumbers++;
}
else
{
oddNumbers++;
}
totalNumbers++;
}