JavaScript中while循环练习
程序员文章站
2022-03-16 10:38:14
...
- 1-100奇偶数求和
var num = 1;
var sum = 0;
var odd = 0;
while(num <= 100){
if(num % 2 == 1){
console.log(num + "是奇数");
odd = odd + num;
}else{
console.log(num + "是偶数");
sum = sum + num;
}
num++;
}
- 现在有1000元,一年利息为4%,多少年后会超过5000元;
var money = 1000;
var year = 1;
var flag = true;
while(flag){
money = money * 1.04;
year++;
if(money >= 5000){
flag = false;
}
console.log("第" + year + "年" + "money = " + money + "元");
}
- 0000-20220所有 平年 + 所有闰年
var year1 = 0000;
var count1 = 0;//计数普通闰年
var count2 = 0;//计数实际闰年
while(year1 <= 2020){
if(year1 % 4 == 0 && year1 % 100 != 0){
console.log(year1 + "为普通闰年");
count1++;
}else if(year1 % 400 == 0){
console.log(year1 + "为世纪闰年");
count2++;
}
year1++;
}
console.log(count1);
console.log(count2);
-
一张纸厚度0.1mm 对折一次厚度翻倍,对折多少次超过珠穆朗玛峰8848m;
var weight = 0.1;//8848 * 100 * 10
var count = 0;
while(weight <= 8848 * 100 * 10){
weight *= 2;
count++;
}
console.log(count);
- 操场大约一百多人,三个三个排剩一个,四个四个排剩二个,五个五个排剩二个;
var num = 100;//num = Math.floor(num / 3) + 1 =
var flag = true;
while(flag){
if(num % 3 == 1 && num % 4 == 2 && num % 5 == 2){
console.log(num);
flag = false;
}
num++;
}
- 石头剪刀布
var success = 0;
var lose = 0;
while (success < 2 && lose < 2 ){
var player = prompt("请输入你的猜拳");
if(player != "" && player != null){
var computer = Math.floor(Math.random() * 3);
switch (computer){
case 0:
computer = "剪刀";
break;
case 1:
computer = "石头";
break;
case 2:
computer = "布";
break;
}
console.log("computer = " + computer);
if(player == computer){
console.log("平局")
}else if (player == "剪刀" && computer == 2 || player == "石头" && computer == 0 || player == "布" && computer == 3){
console.log("玩家赢");
success++;
}else{
console.log("电脑赢");
lose++;
}
}else{
console.log("输入有误");
}
}
console.log(success);
if(success == 2){
console.log("玩家取得最终胜利");
}else{
console.log("电脑取得最终胜利");
}
- 水箱有水120立方,每小时进水12立方,出水30立方,多少小时排完水
var hour = 0;
var water = 120;
while(water > 0){
hour++;
//water = 120 - (30 - 12) * hour;
water += 18;
water -= 30;
}
console.log(hour);
下一篇: DP(状压进阶二)
推荐阅读
-
js使用for循环查询数组中是否存在某个值_javascript技巧
-
JavaScript中关于for循环删除数组元素内容时出现的问题
-
php中循环之for()、while()、foreach()用法_PHP教程
-
javascript中利用数组实现的循环队列代码_javascript技巧
-
js和jquery中循环的退出和继续学习记录_javascript技巧
-
C#中while循环语句用法实例详解
-
C#中while循环语句用法实例详解
-
C#中循环语句:while、for、foreach的使用
-
Python中for循环和while循环的基本使用方法
-
Python中for循环和while循环的基本使用方法