欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

JavaScript中while循环练习

程序员文章站 2022-03-16 10:38:14
...
  1. 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++;
			}
  1. 现在有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 + "元");
}
  1. 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);
  1.  一张纸厚度0.1mm 对折一次厚度翻倍,对折多少次超过珠穆朗玛峰8848m;
    
var weight = 0.1;//8848 * 100 * 10
		var count = 0;
		
		while(weight <= 8848 * 100 * 10){
			weight *= 2;
			count++;
		}
		console.log(count);
		
		
  1. 操场大约一百多人,三个三个排剩一个,四个四个排剩二个,五个五个排剩二个;
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++;
			}
  1. 石头剪刀布
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("电脑取得最终胜利");
		}
		
  1. 水箱有水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);
相关标签: while