黑色星期五题目描述有些西方人比较迷信如果某个月的 13 号正好是星期五他们就会觉得不太吉利用古人的说法就是诸事不宜。请你编写一个程序统计出在某个特定的年份中出现了多少次既是 13 号又是星期五的情形以帮助你的迷信朋友解决难题。说明:一年有 365 天闰年有 366 天所谓闰年即能被 4 整除且不能被 100 整除的年份或是既能被 100 整除也能400 整除的年份;已知 1998 年 1 月 1
#include <iostream>
using namespace std;
// 判断是否为闰年
bool isLeapYear(int year) {
if (year % 4 == 0 && year % 100 != 0) {
return true;
} else if (year % 400 == 0) {
return true;
} else {
return false;
}
}
// 获取某个月的天数
int getDaysOfMonth(int year, int month) {
if (month == 2) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
} else if (month == 4 || month == 6 || month == 9 || month == 11) {
return 30;
} else {
return 31;
}
}
// 获取某一天是星期几,返回值为 0-6,0 表示星期日,1 表示星期一,以此类推
int getWeekday(int year, int month, int day) {
if (month < 3) {
month += 12;
year--;
}
int c = year / 100;
year %= 100;
int week = year + year / 4 + c / 4 - 2 * c + 26 * (month + 1) / 10 + day - 1;
week = (week % 7 + 7) % 7;
return week;
}
int main() {
int year;
cin >> year;
int count = 0;
for (int month = 1; month <= 12; month++) {
if (getWeekday(year, month, 13) == 5) {
count++;
}
}
cout << count << endl;
return 0;
}
``
原文地址: https://www.cveoy.top/t/topic/hRWS 著作权归作者所有。请勿转载和采集!