JavaScript-for循环练习
2018-12-09 本文已影响0人
邵毅超
1-100之间所有7的倍数的个数及总和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
function sum(){
var sum = 0;
for(var i = 1; i < 100; i++){
if(i % 7 == 0){sum+=i;}
}
return sum;
}
document.write('总和:'+sum())
</script>
<script type="text/javascript">
function num(){
var num = 0;
for(var i = 1; i < 100; i++){
if(i % 7 == 0){num++;}
}
return num;
}
document.write('计数:'+num())
</script>
</body>
</html>
1-100之间的奇数和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1-100之间的奇数和</title>
</head>
<body>
<script>
var sum = 0;
for(var i = 1; i <= 100; i++){
if(i % 2!= 0){
sum += i;
}
}
document.write(sum+"<br>");
sum = 0;
for(var i=1;i<100;i+=2){
sum+=i;
}
document.write(sum);
</script>
</body>
</html>
1-100质数求和
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>1-100质数求和</title>
</head>
<body>
<div id="wrap"></div>
<script type="text/javascript">
var wrap = document.getElementById("wrap");
var str = "";
for (var i = 2; i <= 100; i++) {
var count = 0;
for (var j = 1; j <= i; j++) {
if( i%j ==0 ){
count++;
}
}
if (count == 2) {
str += "<span>" + i + "</span><br>";
}
count = 0;
}
wrap.innerHTML = str;
</script>
</body>
</html>
乘法口诀表
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>乘法口诀表</title>
</head>
<body onload="step()">
<script type="text/javascript" >
function step(){
for(i=1;i<=9;i++){
for(j=1;j<=i;j++){
document.write(i+"x"+j+"="+i*j +"   ");
}document.write("<br/>");
}
}
</script>
</body>
</html>
判断质数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>质数</title>
</head>
<body>
<script type="text/javascript">
var num =Number(prompt("请输入一个正整数,判断此数是不是素数"));//要判断的数
var flag = true;//假设变量 值为true 是素数
for( var i = 2 ; i < num ; i++ ){
if( num % i == 0 ){//满足这个条件 说明有因子了 不是素数
flag = false;//不是素数
break;
}
}
//如果假设成立
if( flag && num != 1 ){ //1不是素数
document.write( num + "是素数" );
}else{
document.write( num + "不是素数" );
}
</script>
</body>
</html>
水仙花数
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>水仙花数</title>
</head>
<body>
<script type="text/javascript">
var a, b, c;
for (var i = 100; i < 1000; ++i) {
a = i % 10;
b = ((i / 10) % 10);
b = parseInt(b);
c = i / 100;
c = parseInt(c);
if (i == a * a * a + b * b * b + c * c * c)
document.write(i + "<br />");
}
</script>
</body>
</html>