赛马网基本算法之--日期倒计时

题目描述

在经济、科技日益发达的今天,人们对时间的把握越来越严格,对于一个一定影响力的公司的高管来说,他可能要将自己的行程提前安排到下个月。对于普通人来说,他也可能将几天之后的安排已经提前做好。

请设计一个程序计算出今天距离未来的某一天还剩多少天。

假设今天是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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值