14 黑色星期五
作者: xxx时间限制: 1S章节: 一维数组
问题描述 :
13号又是星期五是一个不寻常的日子吗? 13号在星期五比在其他日少吗?为了回答这个问题,写一个程序来计算在n年里13
日落在星期一,星期二…星期日的次数.这个测试从1900年1月1日到 1900+n-1年12月31日.n是一个非负数且不大于400.这里有一些你要知道的: 1900年1月1日是星期一.
4,6,11和9月有30天.其他月份除了2月都有31天.闰年2月有29天,平年2月有28天. 输入说明 :一个整数n(1<= n <= 400). 输出说明 :
七个在一行且相分开的整数,它们代表13日是星期六,星期日,星期一…星期五的次数. 输入范例 : 20 输出范例 : 36
33 34 33 35 35 34
代码:
/*
T14 黑色星期五
算法概述:给定一个数字n,遍历从1900年到n年后
之间的每个月的13号分别是星期几,保存在数组中,然后输出即可
*/
#include<stdio.h>
int getWeek(int year, int month);
int judgeLeapYear(int year);
int main() {
int n = 0, i = 0, j = 0;
int daysCount[8] = {0};// daysCount[1~7]代表星期一、二、三、四、五、六、日的天数
scanf("%d", &n);
for (i = 1900; i <= 1900 + n - 1; i++) {// 年
for (j = 1; j <= 12; j++) {// 月
daysCount[getWeek(i, j)]++;
}
}
printf("%d %d", daysCount[6], daysCount[7]);
for (i = 1; i <= 5; i++) {
printf(" %d", daysCount[i]);
}
printf("\n");
return 0;
}
/*
计算某年某月的13日是星期几,星期一、二、三、四、五、六、日分别返回
1 2 3 4 5 6 7
具体算法:首先计算某年某月13日距离1900年1月1日(星期一)隔了多少天,
然后再推算星期几
*/
int getWeek(int year, int month) {
int days = 0, week = 0;
int i = 0;
for (i = 1900; i < year; i++) {// 处理指定年之前的年
if (judgeLeapYear(i) == 1) {// 闰年
days += 366;
}
else {
days += 365;
}
}
for (i = 1; i < month; i++) {// 处理指定月之前的月
if (i == 2) {
if (judgeLeapYear(year) == 1) {// 特殊情况:闰年2月
days += 29;
}
else {
days += 28;
}
}
else if (i == 4 || i == 6 || i == 9 || i == 11) {
days += 30;
}
else {
days += 31;
}
}
days += 12;// 统计的是增加的天数,所以要将1900年1月1日这一天去掉
week = (days + 1) % 7;
if (week == 0) {
return 7;
}
else {
return week;
}
}
/*
判断某个年份是否为闰年
*/
int judgeLeapYear(int year) {
if ((year % 4 == 0 && year % 100 != 0 ) ||
(year % 400 == 0))
return 1;
return 0;
}