2012-11-06 3 views
1

C++에서 날짜를 계산하는 방법은 무엇입니까? 전체 코드를 작성하지 않아도됩니다. 월과 일을 계산하는 수학을 이해할 수 없습니다!일 수에서 날짜를 계산 하시겠습니까?

예 :가 365을 초과하는 경우

input: 1 
output: 01/01/2012 

input: 10 
output: 01/10/2012 

input: 365 
output: 12/31/2012 

그것은 항상 현재 연도 사용하는 것이, 나는 윤년 탐지를위한 필요가 없습니다 0을 반환합니다.

+1

, 내가 조회 테이블없이 할 수있는 방법을 발견 적이 없다. 12 개 항목, 각 달 ~ 일 *까지 해당 달. 그런 다음 그 달을 찾아서 올려보세요. –

답변

8

예를 들어 날짜 계산 라이브러리를 사용하십시오. 미세 Boost Date_Time 라이브러리가있는 이것은 표준 라이브러리와도 매우 어렵지 않다

using namespace boost::gregorian; 
date d(2012,Jan,1);      // or one of the other constructors 
date d2 = d + days(365);    // or your other offsets 
1

된다. 나는 C 프로그래머합니다 (C++ <ctime> 더 재진입 gmtime 기능이 없습니다) 같은 C++ 코드를 작성하는 경우 용서 :

#include <time.h> 
#include <cstdio> 

int main(int argc, char *argv[]) 
{ 
    tm t; 
    int daynum = 10; 

    time_t now = time(NULL); 
    gmtime_r(&now, &t); 
    t.tm_sec = 0; 
    t.tm_min = 0; 
    t.tm_hour = 0; 
    t.tm_mday = 1; 
    t.tm_mon = 1; 
    time_t ref = mktime(&t); 
    time_t day = ref + (daynum - 1) * 86400; 
    gmtime_r(&day, &t); 
    std::printf("%02d/%02d/%04d\n", t.tm_mon, t.tm_mday, 1900 + t.tm_year); 

    return 0; 
} 

죄송합니다,이 없이 윤년 감지 할 수있는 온건 한 방법을 알고하지 않습니다.

1

간단한 는 1 년 3백65일 가정 프로그램에서 스 니펫 : 라이브러리 함수없이

int input, day, month = 0, months[13] = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; 

while (input > 365) { 
    // Parse the input to be less than or equal to 365 
    input -= 365; 
} 

while (months[month] < input) { 
    // Figure out the correct month. 
    month++; 
} 

// Get the day thanks to the months array 
day = input - months[month - 1]; 
관련 문제