【发布时间】:2015-07-05 14:24:57
【问题描述】:
13 号星期五真的是不寻常的事件吗?
也就是说,每月 13 日在星期五的频率是否比一周中的任何其他日子少?要回答这个问题,请编写一个程序来计算 在给定的 N 年期间内,每个月的 13 日在星期日、星期一、星期二、>星期三、星期四、星期五和星期六出现的频率。 >测试时间段是从 1900 年 1 月 1 日到 1900 年 12 月 31 日+N-1,持续 > 给定的年数,N 为正且不超过 400。
这是我所拥有的:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
using namespace std;
int main(){
ifstream fin("fridayin.txt");
ofstream fout("fridayout.txt");
int N;
fin >> N;
int current_year, end_year = 1900 + N - 1, current_day = 1; //set current_year, end_year, and current_day to 1(Monday)
int daycounter[7] = { 0 }; //this will record how many times a day occurs on the 13th
int current_month = 1;
int day;
for (current_month = 1; current_month <= 12; current_month++){
for (current_year = 1900; current_year <= end_year; current_year++){ //jan 13=saturday
int yp = current_year - 1900;
if (current_year < 2000){ //2000 is a leap year
day = (6 + yp + yp / 4 - yp / 100) % 7;
daycounter[day]++; //increment the day counter
}
else if (current_year > 2000){ //check if it's after 2000, if it is add 1 to 6 to get 0 (mod 7)
day = (yp + yp / 4 - yp / 100) % 7;
daycounter[day]++; //increment the day counter
}
}
}
int i;
for (i = 0; i < 7; i++){
fout << daycounter[i] << ' ';
}
return 0;
}
我计算的是 1 月 13 日,然后是 2 月 13 日,... 12 月 13 日。
这是输入:
20
正确的输出:
36 33 34 33 35 35 34
我的输出:
48 36 36 24 24 36 36
我想我知道出了什么问题,因为 1900 年 1 月 13 日是星期六,所以我将其设为 6 mod 7,但 1900 年 2 月 13 日和其他月份的情况并非如此。我必须更改方程式并创建一个 if 语句,但这会非常长。
【问题讨论】:
-
你的问题是什么?
-
看在上帝的份上,不要为此使用手工制作的 C++。在没有实体库的情况下,时间是最需要处理的 PITA 事情之一。 See this 知道我在说什么。
-
您是否正确计算了所有闰年?你知道如何定义闰年吗?检查一个的功能在哪里?
-
没什么用,不过play.golang.org/p/5sHKZ_hadA
-
@rr- 这是一个竞争问题,很奇怪(但在现实世界中非常有效)日期时间问题被忽略了。
标签: c++