分支结构的练习
判断平/闰年
输入一个年份,判断该年份是平年还是闰年。
平年、闰年的判断标准:
- 年份能被400整除
- 年份能被4整除,但不能被100整除
var yea = prompt("请输入年份:")
var year = parseInt(yea)
if(year%400==0||(year%4==0&&year%100!=0))
{
console.log("闰年")
}
else
{
console.log("平年")
}
输出结果:
判断成绩等级
输入学生该门课程的成绩,判断该学生成绩的等级。
成绩等级的判断标准:
- 90 - 100分 :A
- 80 - 89分 : B
- 70 - 79分 : C
- 60 - 69分 : D
- 59分及以下 : E
用多分支语句写
var grad = prompt("学生成绩:")
var grade = parseInt(grad)
if(grade>=90)
{
console.log("A")
}
else if(grade>&#61;80&&grade<90)
{
console.log("B")
}
else if(grade>&#61;70&&grade<80)
{
console.log("C")
}
else if(grade>&#61;60&&grade<70)
{
console.log("D")
}
else
{
console.log("E")
}
输出结果&#xff1a;
用switch…case写
var grad &#61; prompt("输入成绩&#xff1a;")
var grade &#61; parseInt(grad)
switch(parseInt(grade/10))
{
case 10:
case 9: console.log("A");
break;
case 8: console.log("B");
break;
case 7: console.log("C");
break;
case 6: console.log("D");
break;
default: console.log("E");
}
输出结果&#xff1a;
找出三个数中最大的数
找出2、3、8三个数中最大的数。
找出最大数的思路&#xff1a;
- 先对两个数a、b进行比较&#xff0c;找出其中最大的数max
- 再用max和剩下的一个数c进行比较
实现一
var a &#61; 2
var b &#61; 3
var c &#61; 8
var max
max &#61; a>b?a:b
max &#61; max>c?max:c
console.log(max)
输出结果&#xff1a;
实现二
var a &#61; 2
var b &#61; 3
var c &#61; 8
var max
max &#61; ((a>b?a:b)>c)?(a>b?a:b):c
console.log(max)
输出结果&#xff1a;