Skip to content

Instantly share code, notes, and snippets.

@torazuka
Created September 19, 2011 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save torazuka/1226126 to your computer and use it in GitHub Desktop.
Save torazuka/1226126 to your computer and use it in GitHub Desktop.
Chapter09_drill01_PPPC++
/*
『ストラウストラップのプログラミング入門』
9章ドリル1(9.4.1バージョン, データだけ持つstruct)
*/
#include "../../std_lib_facilities.h"
struct Date{
int y;
int m;
int d;
};
bool leapyear(int y)
// うるう年ならtrueを返す
{
bool result = false;
if(y % 4 == 0 && y % 100 != 0){
result = true;
}
if(y % 400 == 0){
result = true;
}
return result;
}
int get_days_in_month(int y, int m)
// その月の日数を返す
{
int result = 31;
switch(m){
case 2:
result = (leapyear(y)) ? 29 : 28;
break;
case 4: case 6: case 9: case 11:
result = 30;
break;
}
return result;
}
void init_day(Date& dd, int y, int m, int d)
// (y, m, d)が有効な日付かどうかを確認する
// そうである場合はddを初期化する
{
if(y < 1){
error("bad year");
}
if(m < 1 || 12 < m){
error("bad month");
}
if(d < 1){
error("bad day");
}
if(get_days_in_month(y, m) < d){
error("over day");
}
dd.y = y;
dd.m = m;
dd.d = d;
}
void add_year(Date& dd, int n)
{
dd.y += n;
}
void add_month(Date& dd, int n)
{
const int months_in_year = 12;
// 月数nを現在の月に足すと、12を超える場合、翌年に繰り越す
if(months_in_year < (dd.m + n)){
add_year(dd, 1);
add_month(dd, n - months_in_year);
} else {
dd.m += n;
}
}
void add_day(Date& dd, int n)
{
int days_in_month = get_days_in_month(dd.y, dd.m);
// 日数nを現在の日に足すと、当月内の日数を超える場合、翌月に繰り越す
if(days_in_month < (dd.d + n)){
add_month(dd, 1);
add_day(dd, n - days_in_month);
} else {
dd.d += n;
}
}
ostream& operator<<(ostream& os, const Date dd)
{
return os << '(' << dd.y
<< ',' << dd.m
<< ',' << dd.d << ')';
}
void f()
{
Date today;
init_day(today, 1978, 6, 25);
Date tomorrow;
tomorrow = today;
add_day(tomorrow, 1);
cout << today << '\n' << tomorrow << endl;
}
int main()
{
f();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment