当前位置:编程学习 > C/C++ >>

C++日期类编程题

写一个日期类Date,具有如下功能:
1. 具有年月日时分秒等基本数据。
2. 能使用如下方式进行初始化或声明:
a) Date d1(2008,1,14)
b) Date D2(2008,1,14,13,)//2008年1月14日13:00:00
c) Date D3(2008,1,14,13,5) //2008年1月14日13:05:00
d) Date D4(2008,1,14,13,5,7) //2008年1月14日13:05:07
e) Date D5(“2008-1-14 13:5:7”)/年月日之间用一个-号分隔,时间部分用:号分隔,日期与时间之间有一个空格。
3. 能判断是否是闰年
4. 能获取年、月、日、时、分、秒。
5. 能计算一个日期加上若干年,有AddYear(int n)这样的成员函数,对月、日、时、分、秒,也有类似的函数
6. 具有输入、输出流,输入的格式为年、月、日、时、分、秒用空白字符间隔分别输入,输出的格式采用24小时制,如“2008-01-14 13:05:07”
7. 提供日期对象之间的关系运算符的重载,能进行==,!=,<,>,<=,>=等运算符的比较
答案:#include &lt;iostream&gt;
#include &lt;stdio.h&gt;
#include &lt;time.h&gt;
#include "12.h"
using namespace std;

int main(){

myfun myclas;

struct tm *local;
time_t t = time(NULL);
local=gmtime(&t);
cout&lt;&lt;"当前系统时间:"&lt;&lt;1900+local-&gt;tm_year&lt;&lt;"年"&lt;&lt;1+local-&gt;tm_mon&lt;&lt;"月"&lt;&lt;local-&gt;tm_mday&lt;&lt;"日"&lt;&lt;endl;




int year=1900+local-&gt;tm_year;

int month=1+local-&gt;tm_mon;
int day=local-&gt;tm_mday;

int mon[]={31,28,31,30,31,30,31,31,30,31,30,31};
int a=year-myclas.year;

int i=0;
int j=0;
int mon1=0;
int mon2=0;
for (i=0;i&lt;myclas.month;i++)
{
int mon1=mon1+mon[i];
}
for (i=0;i&lt;month;i++)
{
int mon2=mon2+mon[i];
}
int monday=mon1-mon2;
int c=myclas.day-day;

if (month-myclas.month&lt;0)
a=a-1;


if ((year/100)||(year/4)&&(year/400))
{

cout&lt;&lt;"是闰年";


cout&lt;&lt;"输入的年份与本地时间的间隔是:"&lt;&lt;a*366+c&lt;&lt;"天"&lt;&lt;endl;

}

else
{

cout&lt;&lt;"不是闰年";


cout&lt;&lt;"输入年份与本地年份间隔是:"&lt;&lt;a*365+c&lt;&lt;"天"&lt;&lt;endl;
}

return 0;
}

这是头文件:12.h

#ifndef time_h
#define time_h
class myfun
{

public:
int day,month,year;
myfun(){
std::cout&lt;&lt;"year:";
std::cin&gt;&gt;year;
std::cout&lt;&lt;std::endl;
std::cout&lt;&lt;"month:";
std::cin&gt;&gt;month;
std::cout&lt;&lt;std::endl;
std::cout&lt;&lt;"day:";
std::cin&gt;&gt;day;
std::cout&lt;&lt;std::endl;

}
};
#endif
慢慢看,我写的,写完放在电脑找了很久,找到了,这个程序考虑了几种情况,日期是可以手动输入的,判断输入的是不是闰年,然后计算输入的日期跟系统本身的日期相差多少天。至于你要的时分秒,你仔细看time的头文件的源代码,我这里是给你参考的,还有其他细节,你应该可以解决,你不是想我给做好的你吧,那你什么都学不到的也。。输出的方面可以按你的喜好改。算是给你提示了。

上一个:C++鐨勮櫄缁ф壙 - 宸茶В鍐?- 鎼滄悳闂棶
下一个:c语言和c++

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,