while循环应用(各种小练习)
练习1:1+…+100等于
let i = 1,num=0;
while(i<=100){
num+=i;
i++;
}
console.log(num);
练习2:100以内奇数项的和与偶数项的和
let odd=0,even=0,i=1;
while(i<=100){
if(i%2==0){
even+=i;
}else{
odd+=i;
}
i++;
}
console.log("奇数是:"+odd+",偶数是:"+even);
练习3:水仙花数
const readline = require('readline-sync');
let i = true;
while (i) {
console.log('请用户输入一个三位数,输入0退出');
let sum = readline.question();
if(sum==0){
break;
}
if (sum.length == 3) {
sum -= 0;
let gw, sw, bw;
gw = sum % 10;
sw = parseInt(sum % 100 / 10);
bw = parseInt(sum / 100);
if (sum == (gw ** 3 + sw ** 3 + bw ** 3)) {
console.log(`${sum}是水仙花数`);
} else {
console.log(`${sum}不是水仙花数`);
}
} else {
console.log('非法输入');
}
}
练习4:判断回文12321
const readline = require('readline-sync');
let i = true;
while (i) {
console.log('请用户输入一个数,输入0退出');
let sum = readline.question();
if (sum == 0) {
break;
}
gw = sum % 10;
sw = parseInt(sum % 100 / 10);
bw = parseInt(sum % 1000 / 100);
qw = parseInt(sum % 10000 / 1000)
ww = parseInt(sum / 10000)
len = sum.length;
if (gw==ww&&sw==qw) {
console.log(`${sum}是回文数`);
} else {
console.log(`${sum}不是回文数`);
}
}
练习5:判断回文,while和for循环嵌套
const readline = require('readline-sync');
let i = true;
while (i) {
console.log('请用户输入一个数,输入0退出');
let sum = readline.question();
if (sum == 0) {
break;
}
str = sum.length;
let s = true;
for(let j=0,o=str-1;j<=parseInt(str/2);j++,o--){
if(sum[j]!=sum[o]) {
s=false;
}
}
if(s==true){
console.log('是回文');
}else{
console.log('不会回文');
}
}
|