2014年1月30日木曜日

開発環境

C++実践プログラミング (スティーブ オウアルライン (著)、Steve Oualline (原著)、Steve Oualline(原著)、望月 康司(翻訳)、クイープ(翻訳) 、オライリー・ジャパン)のⅠ部(基礎)の7章(プログラミングの手順)、7.15(プログラミング実習)、実習 7-2.を解いてみる。

その他参考書籍

実習 7-2.

コード

sample.cpp

#include <iostream>

int main()
{
    int days;
    int begin_year;
    int begin_month;
    int begin_day;
    int end_year;
    int end_month;
    int end_day;
    int i;
    int months[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    std::cout << "開始日を入力(年、月、日): ";
    std::cin >> begin_year >> begin_month >> begin_day;
    std::cout << "終了日を入力(年、月、日): ";
    std::cin >> end_year >> end_month >> end_day;
    
    days = 0;
    for (i = begin_year; i < end_year; i++){
        if ((i % 400 == 0) || ((i % 4 == 0) && (i % 100 != 0))) {
            days += 366;
        } else {
            days += 365;
        }
    }
    for (i = 0; i < begin_month - 1; i++) {
        if (i == 1 && ((begin_year % 400 == 0) ||
                      ((begin_year % 4 == 0) && (begin_year % 100 != 0)))) {
            days -= 29;
        } else {
            days -= months[i];
        }
    }
    days = days - (begin_day - 1);
    for (i = 0; i < end_month - 1; i++) {
        if (i == 1 && ((end_year % 400 == 0) ||
                      ((end_year % 4 == 0) && (end_year % 100 != 0)))) {
            days += 29;
        } else {
            days += months[i];
        }
    }
    days += end_day;
    std::cout << days << "日(開始日、終了日を含む)\n";
    return (0);
}

Makefile

#
# FSFのg++コンパイラ用のMakefile
#
CC=g++
CFLAGS=-g -Wall
all: sample

sample: sample.cpp
 $(CC) $(CFLAGS) -o sample sample.cpp

clean:
 rm sample

入出力結果(Terminal)

$ make
g++ -g -Wall -o sample sample.cpp
$ ./sample
開始日を入力(年、月、日): 2000 1 1
終了日を入力(年、月、日): 2000 1 1
1日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 2000 1 1
終了日を入力(年、月、日): 2000 1 2
2日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 2000 1 1
終了日を入力(年、月、日): 2000 2 1
32日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 2000 1 1
終了日を入力(年、月、日): 2000 1 2
2日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 2000 1 1
終了日を入力(年、月、日): 2000 2 2
33日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 2000 2 1
終了日を入力(年、月、日): 2000 4 2
62日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 1999 2 2
終了日を入力(年、月、日): 2001 2 2
732日(開始日、終了日を含む)
$ ./sample
開始日を入力(年、月、日): 1899 2 2
終了日を入力(年、月、日): 1901 2 2
731日(開始日、終了日を含む)
$

0 コメント:

コメントを投稿