思路:此类有关月份的题目可以把月份存在一个数组(列表)里,再用判断是否为闰年就可解决该月天数的问题。然后再标记下几号和周几即可得出答案。(最后补充了暴力求解)
C:
#include<iostream.h>
void main()
{
int sum=0, week = 6;//sum:公里数 week:当天为周几,起初2000.1.1为周六
//从2000到2020
for (int year = 2000; year <= 2020; year++)
{
int d[13] = {
0,31,28,31,30,31,30,31,31,30,31,30,31};//数组为每个月份的天数
if(year%4==0)//2000->2020中的闰年,使闰年2月份天数为29天
d[2] = 29;
for (int month = 1; month <= 12; month++)//循环月份
for (int day = 1; day <= d[month]; day++,week++) //循环天数,再使week++
{
if(week==8)//若week为8,则重回周一
week=1;
if(day==1 || week==1)//当天为周一或一号时,跑两公里
sum+=2;
else //当天不为周一或一号时,跑一公里
sum+=1;
if(year==2020 && month==10 && day==1)//2020.10.1输出公里数
cout<<sum<<endl;
}
}
}
Java:
public class GroupC_D11 {
public static void main(String[]args){
int sum = 0; //公里数
int week = 6; //当天为周几,起初2000.1.1为周六
for (int year = 2000; year <= 2020; year++) {
//从2000到2020
int []d = {
0,31,28,31,30,31,30,31,31,30,31,30,31}; //数组为每个月份的天数
if(year%4==0){
//2000->2020中的闰年
d[2] = 29; //使闰年2月份天数为29天
}
for (int month = 1; month <= 12; month++) {
//循环月份
for (int day = 1; day <= d[month]; day++,week++) {
//循环天数,再使week++
if (week==8){
//若week为8,则重回周一
week=1;
}
if(day==1 | week==1){
//当天为周一或一号时,跑两公里
sum+=2;
}else{
//当天不为周一或一号时,跑一公里
sum+=1;
}
if(year==2020 & month==10 & day==1){
//2020.10.1输出公里数
System.out.println(sum);
}
}
}
}
}
}
python:
week = 6 #公里数
sum = 0 #当天为周几,起初2000.1.1为周六
for year in range(2000,2021): #从2000到2020
d = [0,31,28,31,30,31,30,31,31,30,31,30,31] #列表为每个月份的天数
if year%4 == 0: #2000->2020中的闰年,使闰年2月份天数为29天
d[2] = 29
for month in range(1,13): #循环月份
for day in range(1,d[month]+1): #循环天数
if week == 8: #若week为8,则重回周一
week = 1
if day == 1 or week == 1: #当天为周一或一号时,跑两公里
sum = sum + 2
else: #当天不为周一或一号时,跑一公里
sum = sum + 1
week = week + 1
if year == 2020 and month == 10 and day == 1: #2020.10.1输出公里数
print(sum)
答案:8879
用Java写了个暴力求解,其他语言类似
public class BaoLi {
public static void main(String[]args){
int sum = 0;//公里数
int week = 6;//当天为周几,起初2000.1.1为周六
int day = 0;
for (int year = 2000;year <= 2020;year++){
if (year%4==0){
//闰年
for (int month = 1;month <= 12;month++){
if (month==2){
//day为该月份的天数
day = 29;
}else if (month==4|month==6|month==9|month==11){
day = 30;
}else {
day = 31;
}
for (int date = 1;date <= day;date++,week++){
if (week==8){
week = 1;
}
if (date==1|week==1){
sum += 2;
}else {
sum += 1;
}
if (year==2020&month==10&date==1){
System.out.println(sum);
}
}
}
}else{
//直接把上面的复制粘贴,把2月份的day改为28
for (int month = 1;month <= 12;month++){
if (month==2){
day = 28;
}else if (month==4|month==6|month==9|month==11){
day = 30;
}else {
day = 31;
}
for (int date = 1;date <= day;date++,week++){
if (week==8){
week = 1;
}
if (date==1|week==1){
sum += 2;
}else {
sum += 1;
}
}
}
}
}
}
}
转载:https://blog.csdn.net/ccccduo/article/details/115475124
查看评论