题目描述
在经济、科技日益发达的今天,人们对时间的把握越来越严格,对于一个一定影响力的公司的高管来说,他可能要将自己的行程提前安排到下个月。对于普通人来说,他也可能将几天之后的安排已经提前做好。
请设计一个程序计算出今天距离未来的某一天还剩多少天。
假设今天是2015年10月18日。
输入
输入一个日期格式为yyyy-MM-dd,不考虑日期是否小于今天。
|
样例输入
2015-10-19
|
输出
输出一个数字表示今天(2015年10月18日)距离该日期还剩多少天。
|
样例输出
1
|
时间限制
C/C++语言:1000MS 其它语言:3000MS |
内存限制
C/C++语言:65536KB 其它语言:589824KB |
*#include<iostream>
#include<ctime>
using namespace std;
int main(){
struct tm now = {0};
now.tm_year = 2015-1900;
now.tm_mon = 10-1;
now.tm_mday = 18;
time_t now_sec = mktime(&now);
char input[100];
gets(input);
char *pch = strtok(input, "-");
char * res[3];
int i = 0;
while (pch != NULL){
res[i++] = pch;
pch = strtok(NULL, "-");
}
struct tm input_t = {0};
input_t.tm_year = atoi(res[0]) - 1900;
input_t.tm_mon = atoi(res[1]) - 1;
input_t.tm_mday = atoi(res[2]);
time_t input_second = mktime(&input_t);
cout << (input_second - now_sec) / 24 / 3600 << endl;
}
主要思路是将起始时间的秒数算出来,然后再计算出输入的日期的秒数,最后将秒数转换为天数即为倒计时的天数。在上面的程序中使用了字符串分割的方法来
分割年、月、日。其还可以利用sscanf利用类似正则表达式来处理。其中关于时间的几个函数需要注意:
time_t是一个long型的数来表示秒数;
tm为时间结构体,其中包括了year,month,day等属性;
mktime是将一个表示时间的结构体tm转换为秒数(从1900年开始)time_t;
localtime()将time_t转换为一个指向tm的指针;
asctime()转换为可读的时间。
#include<iostream>
#include<ctime>
#include<cstdio>
using namespace std;
int main(){
struct tm now = {0};
now.tm_year = 2015-1900;
now.tm_mon = 10-1;
now.tm_mday = 18;
time_t now_sec = mktime(&now);
struct tm input_t = {0};
int year, month, day;
scanf("%d-%d-%d", &year, &month, &day);
input_t.tm_year = year - 1900;
input_t.tm_mon = month - 1;
input_t.tm_mday = day;
time_t input_second = mktime(&input_t);
cout << (input_second - now_sec) / 24 / 3600 << endl;
return 0;
}