有人能告诉我我的代码有什么问题吗?回归正确的世纪。这是为了返回正确的世纪,(例如,1905年返回20,年1700返回17)。约束为1≤年≤2005。输入为正整数(年)。
function centuryFromYear(year) {
switch (year) {
case ((year >= 1) && (year < 101)):
return 1;
break;
case ((year > 100) && (year < 201)):
return 2;
break;
case ((year > 200) && (year < 301)):
return 3;
break;
case ((year > 300) && (year < 401)):
return 4;
break;
case ((year > 400) && (year < 501)):
return 5;
break;
case ((year > 500) && (year < 601)):
return 6;
break;
case ((year > 600) && (year < 701)):
return 7;
break;
case ((year > 700) && (year < 801)):
return 8;
break;
case ((year > 800) && (year < 901)):
return 9;
break;
case ((year > 900) && (year < 1001)):
return 10;
break;
case ((year > 1000) && (year < 1101)):
return 11;
break;
case ((year > 1100) && (year < 1201)):
return 12;
break;
case ((year > 1200) && (year < 1301)):
return 13;
break;
case ((year > 1300) && (year < 1401)):
return 14;
break;
case ((year > 1400) && (year < 1501)):
return 15;
break;
case ((year > 1500) && (year < 1601)):
return 16;
break;
case ((year > 1600) && (year < 1701)):
return 17;
break;
case ((year > 1700) && (year < 1801)):
return 18;
break;
case ((year > 1800) && (year < 1901)):
return 19;
break;
case ((year > 1900) && (year < 2001)):
return 20;
break;
case ((year > 2000) && (year <=2005)):
return 21;
break;
}
}
答案 0 :(得分:1)
如果您想检查范围,则无法使用case
,它需要准确的值。
switch (expression) {
case value1:
//Statements executed when the result of expression matches value1
[break;]
case value2:
//Statements executed when the result of expression matches value2
[break;]
...
case valueN:
//Statements executed when the result of expression matches valueN
[break;]
default:
//Statements executed when none of the values match the value of the expression
[break;]
}
针对您的问题的更通用的解决方案将类似于此:
function centuryFromYear(year) {
return Math.floor((year-1)/100)+1
}
答案 1 :(得分:1)
只需将year - 1
除以100
,然后像这样添加1
:
function centuryFromYear(year) {
return Math.floor((year - 1) / 100) + 1;
}
/* Example: */
var year = parseInt(prompt('Enter a year: '));
alert('The century is: ' + centuryFromYear(year));