2016-08-20 2 views
1

저는 크리스마스까지 며칠인지 알려주는 프로그램을 작성하려고합니다. 나는 time.h 라이브러리와 함께 일한 적이 없기 때문에 대부분 그 라이브러리를 사용하고있다. 나는 현재의 시간을 충분히 쉽게 얻을 수는 있지만 문제는 크리스마스 시간에 정보를 입력하는 방법을 정확히 모르겠다는 것입니다. difftime 계산이 엉망입니다. 아래의 코드는 실행될 때마다 다른 번호를 출력하지만, 내가 무엇을 시도하든 관계없이 작동시킬 수는 없습니다.크리스마스 때까지의 시간을 C로 계산하시오

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
time_t currentDate; 
time (&currentDate); 

struct tm * now; 
now = localtime (&currentDate); 

struct tm xmas; 
xmas = *localtime(&currentDate); 
xmas.tm_yday = 359; 

double seconds = difftime(asctime(&xmas),asctime(&now)); 

double days=seconds/86400; 

printf("%g days\n", days); 


return 0; 
} 
+1

당신은 크리스마스가 올해의 359 번째 날이라고 말하고 있습니까? 나는 항상 그런 것은 아니라고 확신합니다. 12 월 30 일이라면 어떻게됩니까? – gnasher729

+0

'time' 함수는'tm_yday'에 올바른 값을 입력하고 있다는 것을 모르고 다른 요소는 무시해야합니다. 정확한 접근 방법은 http://stackoverflow.com/a/9575245/2564301을 참조하십시오. – usr2564301

+0

'asctime()'함수가'char *'를 반환하기 때문에, 그 코드는 경고없이 컴파일되어서는 안된다. 또한,'asctime()'은 정적 데이터에 대한 포인터를 반환한다. 두 번째 호출 할 때 이전 값을 덮어 씁니다.즉, 어느 값이'difftime()'에 전달되는지 알지 못한다는 것을 의미합니다 - 한 레벨에서는'difftime()'에 대한 호출이 부정확하기 때문에 중요하지 않습니다. 그러나 당신이 두 개의 문자열을 필요로한다고 가정하면; 당신은 유용하게'strcmp (asctime (& xmas), asctime (& now))'을 쓸 수 없다. –

답변

2

올바른 경로에 있지만 difftime은 인수로 time_t 유형의 변수를 사용합니다. 따라서 'now'변수를 사용하지 않아도됩니다. 'xmas'변수는 초기화 방법과 약간 다른 방식으로 초기화해야합니다. 그런 다음 mktime()을 사용하여 difftime()에서 사용할 time_t 유형으로 변환 할 수 있습니다. 그래서, C는 좀 짜증에 처리

https://www.gnu.org/software/libc/manual/html_node/Date-and-Time.html

날짜 및 시간 : -

#include <stdio.h> 
#include <stdlib.h> 
#include <time.h> 

int main() 
{ 
    double seconds, days; 
    time_t currentDate; 
    struct tm *xmas, today; 

    time (&currentDate); 

    today = *localtime(&currentDate); 

    xmas = localtime(&currentDate); 
    xmas->tm_mon = 11; // 0 == January, 11 == December 
    xmas->tm_mday = 25; 
    if (today.tm_mday > 25 && today.tm_mon == 11) 
     xmas->tm_year = today.tm_year + 1; 

    seconds = difftime(mktime(xmas),currentDate); 
    days = seconds/86400; 

    printf("%g days\n", days); 

    return 0; 
} 

참조 모든 http://www.cplusplus.com/reference/ctime/difftime/

+0

당신은 올바른 길을 가고 있습니다. 그러나 맨 위에 언급 된 바와 같이 오늘 날짜가 (예 : 12 월 26 일) 일 경우 어떻게해야합니까? –

+0

@CraigEstey 큰 잡기. 12 월 25 일이 지나면 크리스마스의 해가 내년으로 업데이트되도록 방금 업데이트했습니다. –

+0

감사합니다. 도움이되었습니다. xmas-> tm_mon = 11;'&'xmas-> tm_mday = 25;'xmas.tm_mon = 11;이 왜 똑같이 작동하지 않는가? – JM5042

1

첫째, 당신은 libc의 매뉴얼에 날짜와 시간에 대한 장을 읽어야합니다 혼란스럽지 않도록 개념을 잘 이해해야합니다.

주요 작업은 목표 시간이 크리스마스이고 시작 시간이 현재 시간 인 difftime을 호출하는 것입니다. difftime은 time_t 형식으로 시간을 받기 때문에 time_t에는 현재 시간과 크리스마스가 모두 필요합니다. 현재 time_t 형식으로 time() 함수를 사용할 수 있습니다. 구조화 된 달력 시간을 time_t로 변환하려면 mktime()이 필요합니다. 그래서 코드는 다음 끝 :

#include <stdio.h> 
    #include <time.h> 

    int main(void) 
    { 
      time_t now; 
      time_t christmas; 
      struct tm tmp; 
      double seconds; 
      double days; 

      time(&now); 

      tmp.tm_sec = 0; 
      tmp.tm_min = 0; 
      tmp.tm_hour = 0; 
      tmp.tm_mday = 25; 
      tmp.tm_mon = 11; /* December == 11 */ 
      tmp.tm_year = 116; /* 2016 */ 
      tmp.tm_isdst = -1; 

      christmas = mktime(&tmp); 

      seconds = difftime(christmas, now); 
      days = seconds/86400; 

      printf("%g days untils christmas.\n", days); 

      return 0; 
    } 
0

MCU에 일부 부동 소수점 전혀 단위 또는 만 32 비트 float와이없는 double가 처음부터 불가능하거나 또는 높은 함께 제공하여 비용.

여기에는 날짜 차이를 계산하는 정수 전용 버전이 있습니다.

#include <stdio.h> 
#include <stdlib.h> 
#include <limits.h> 

// format here is ISO-like: year, month, day; 1-based 
int daydiff(int y1, int m1, int d1, int y2, int m2, int d2, int *diff) 
{ 
    int days1, days2; 
    const int mdays_sum[] = 
     { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }; 

    // no checks for the other bounds here, feel free to add them 
    if (y1 < 1708 || y2 < 1708) { 
    *diff = INT_MAX; 
    return 0; 
    } 
    // we add the leap years later, so for now 
    // 356 days 
    // + the days in the current month 
    // + the days from the month(s) before 
    days1 = y1 * 365 + d1 + mdays_sum[m1 - 1]; 
    // add the days from the leap years skipped above 
    // (no leap year computation needed until it is March already) 
    // TODO: if inline functions are supported, make one out of this mess 
    days1 += (m1 <= 2) ? 
     (y1 - 1) % 3 - (y1 - 1)/100 + (y1 - 1)/400 : 
     y1 % 3 - y1/100 + y1/400; 

    // ditto for the second date 
    days2 = y2 * 365 + d2 + mdays_sum[m2 - 1]; 
    days2 += (m2 <= 2) ? 
     (y2 - 1) % 3 - (y2 - 1)/100 + (y2 - 1)/400 : 
     y2 % 3 - y2/100 + y2/400; 

    // Keep the signed result. If the first date is later than the 
    // second the result is negative. Might be useful. 
    *diff = days2 - days1; 
    return 1; 
} 

"크리스마스까지 며칠입니까?"라는 질문에 대한 실제 답변은 무엇입니까? 주는

#include <time.h> 
// Or Boxing-Day for our British friends 
int days_until_next_xmas() 
{ 
    int diff; 
    time_t now; 
    struct tm *today; 

    // get seconds since epoch and store it in 
    // the time_t struct now 
    time(&now); 
    // apply timezone 
    today = localtime(&now); 

    // compute difference in days to the 25th of December 
    daydiff(today->tm_year + 1900, today->tm_mon + 1, today->tm_mday, 
      today->tm_year + 1900, 12, 25, &diff); 

    // Too late, you have to wait until next year, sorry 
    if (diff < 0) { 
    // Just run again. 
    // Alternatively compute leap year and add 365/366 days. 
    // I think that running it again is definitely simpler. 
    daydiff(today->tm_year + 1900, today->tm_mon + 1, today->tm_mday, 
      today->tm_year + 1900 + 1, 12, 25, &diff); 
    } 
    return diff; 
} 
int main() 
{ 
    // days_until_next_xmas() returns INT_MAX in case of error 
    // you might want to check 
    printf("Next X-mas in %d days\n", days_until_next_xmas()); 
    exit(EXIT_SUCCESS); 
} 

위 코드는 경계 검사가 그리 많지 않습니다. 특히, int 데이터 유형이 32 비트보다 작은 경우 (현재 대부분의 MCU가 32 비트이지만, 단일 날짜 계산을 위해 아키텍처를 변경하지 않아도됩니다). 이 경우 1900에서 tm->tm_year으로 건너 뛰고 1708의 확인을 변경하십시오. 이는 16 비트 MCU에서 가능합니다. 그것은 8 비트 MCU에 대해 좀 더 복잡해질 것이라고 인정했다.

관련 문제