确定随机数是否可被用户输入整除的程序

时间:2014-04-03 18:42:40

标签: javascript loops if-statement random numbers

用户只能输入1到15之间的数字,所以如果输入不在 范围,输出错误并从函数中“返回”。如果输入是好的, 然后继续

创建一个循环,生成1到100之间的10个随机数。

我知道我的javascript不正确,我已经卡住了。

<html>
<head>
<title></title>

<script type="text/javascript">

function loopNums() {

var usernum = parseInt( document.getElementById("usernum").value );
var msg = ""; // "" is the NULL string
var ;


for( var i = 1; i <= 15; i++ ) {

    if( i % usernum == 0) {

        msg = msg + "<div>" i + "is NOT divisible by " usernum + "</div>";

        msg = msg + "<div>You entered " + i + "</div>";
        sum = sum + i;

    } // ends the for loop

    msg = msg + "<div>The sum is " + sum + "</div>";

    document.getElementById("results").innerHTML = msg;

} // end loopNums() function

</script>

<style type="text/css">

body {
background-color: #996666;
font-family: arial;
color: #996666;
}
#contentwrap {
background-color: #FFCC66;
border: 8px #FF9933 solid;
padding: 20px;
width: 600px;
margin: 20px auto 0px auto;
border-radius: 25px;
text-align: center;
}

#heading {
font-size: 2.2em;
border-bottom: 6px #663399 double;
padding: 10px 0px 10px 0px;
}

#formdiv {
text-align: center;
padding-top: 25px;
}

.formtext {
text-align: center;
font-size: 1.29em;
margin-top: 20px;
}

#usernum {
border: 2px #663399 solid;
}

#result {
font-size: 1em;
color: #FF0000;
}

</style>

</head>

<body>

<div id="contentwrap">

<div id="heading">Loop Practice</div>

<div id="formdiv">

<form>

Enter a number<br />
<input type="text" id="usernum" /><p />

<input type="button" value="Go For It!" onClick="loopNums()" />

</form>

<div id="results"></div>

</div>

</div> <!-- ends div#contentwrap -->

</body>
</html>

1 个答案:

答案 0 :(得分:0)

看看YOUR UPDATED FIDDLE

function loopNums() {
    var usernum = parseInt(document.getElementById("usernum").value);
    var msg = ""; // "" is the NULL string
    var sum = 0;

    if (usernum < 1 || usernum > 15) {
        msg = "Enter a number between 1 and 15";
    } else {
        for (var i = 0; i < 10; i++) {
            var rdnNumber = Math.floor(Math.random() * ( 1 + 100 - usernum )) + usernum;

            if (rdnNumber % usernum === 0)
                msg += "<div style='color: green'>Number generated: " + rdnNumber + ". It is divisible by " + usernum + "!</div>";
            else
                msg += "<div style='color: red'>Number generated: " + rdnNumber + ". It is not divisible by " + usernum + "!</div>";
        }
    }

    document.getElementById("results").innerHTML = msg;
}