系统会为您提供以下信息,但您可能希望自己进行一些研究。
1900年1月1日是星期一。
九月有三十天,
四月,六月和十一月。
其余的都三十一个
仅保存2月,
其中有28个,无论风雨无阻。
在leap年,是二十九。
any年发生在任何可被4整除的年份,但不会发生在一个世纪中,除非将其整除为400。
在二十世纪的第一个月(1901年1月1日至2000年12月31日),有几个星期日?
我已经拿到172,答案是171。我不确定这可能是问题所在,我已经尝试了所有方法,但我一直拿到172。谢谢您的帮助。
public static void main(String args[]){
int year=1901;
boolean isLeapYear=false;
int totalSundays=0;
int currentDay=1;//Starts on a Monday
while(year<=2000){
isLeapYear=false;
if((year%4)==0){
if((year%100)==0 && (year%400)==0){
isLeapYear=true;
} else if((year%100)==0 && (year%400)!=0){
isLeapYear=false;
} else {
isLeapYear=true;
}
}
System.out.println("The Year Is: "+year);
System.out.println("*******************************");
for(int month=1;month<=12;month++){
System.out.println("The Month is: "+month+" currentDay is : "+currentDay);
if(currentDay==7){
totalSundays++;
}
if(month==1 || month==3 || month==5 || month==7 || month==8 || month==10 || month==12){
//January,March,May,July,August,October,December
currentDay+=3;
} else if(month==4 || month==6 || month==9 || month==11){
//April,June,September,November
currentDay+=2;
} else if(month==2 && isLeapYear){
//February has 29 days in a Leap Year
currentDay+=1;
}
if(currentDay>7){
currentDay=currentDay-7;
}
System.out.println("Updated Current Day Is : "+currentDay);
}
System.out.println("*******************************");
year++;
}
System.out.println("The total number of Sundays that fell in the first of the month is: "+totalSundays);
}
最佳答案
您从错误的日子开始。 1901年1月1日实际上是星期二(所以currentDay = 2
。)进行此更改将导致171:http://ideone.com/mh4MJ