首先,我知道你们不喜欢这样的问题被问到,但是我看不出我的代码有什么问题,并希望有人检查一下。话虽如此,我知道我的代码看起来很糟糕,那是因为这一切都必须以一种方法完成。
public static int dayOfWeek(int year, int month, int day) {
int monthCode = 0, centuryCode = 0, numLeapYears = 0, dayOfWeek = 0;
int yearDigits = year % 100;
if((year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))) {
numLeapYears = yearDigits / 2 + 1;
}else {
numLeapYears = yearDigits / 2;
}
if(((year >= 1400) && (year <= 1499)) || ((year >= 1800) && (year <= 1899)) || ((year >= 2200) && (year <= 2299))) {
centuryCode = 2;
}else if(((year >= 1500) && (year <= 1599)) || ((year >= 1900) && (year <= 1999)) || ((year >= 2300) && (year <= 2399))) {
centuryCode = 0;
}else if(((year >= 1600) && (year <= 1699)) || ((year >= 2000) && (year <= 2099)) || ((year >= 2400) && (year <= 2499))) {
centuryCode = 5;
}else if(((year >= 1700) && (year <= 1799)) || ((year >= 2100) && (year <= 2199)) || ((year >= 2500) && (year <= 2599))) {
centuryCode = 4;
}
switch(month) {
case 1: monthCode = 0;
break;
case 2: monthCode = 3;
break;
case 3: monthCode = 3;
break;
case 4: monthCode = 6;
break;
case 5: monthCode = 1;
break;
case 6: monthCode = 4;
break;
case 7: monthCode = 6;
break;
case 8: monthCode = 2;
break;
case 9: monthCode = 5;
break;
case 10: monthCode = 0;
break;
case 11: monthCode = 3;
break;
case 12: monthCode = 5;
break;
}
dayOfWeek = ((centuryCode + yearDigits + numLeapYears + monthCode + day) % 7);
return dayOfWeek;
}//dayOfWeek
我还没有费心评论我的代码,这个函数的目的是计算一个数字(0、1、2等)表示的日期(星期日、星期一等)我的代码有效,但它不输出正确的数字。例如 1969 年 7 月 20 日应该输出为 0,但我的代码输出 3。我似乎找不到这种方法的逻辑缺陷。