读书人

一个书下的小程序为什么运行结果却不

发布时间: 2012-10-21 09:00:07 作者: rapoo

一个书上的小程序,为什么运行结果却不是现在的时间?
[code=C/C++][/code]
#include<iostream>
#include<ctime>
#include<stdio.h>

using namespace std;

class Date {
int mo, da, yr;
public:
Date(time_t);
void display();
};

void Date::display()
{
char year[5];
if (yr < 10)
sprintf(year, "0%d", yr);
else
sprintf(year, "%d", yr);
cout << mo << '/' << da <<'/' << year << endl;
}

Date::Date(time_t now)
{
tm* tim = localtime(&now);
da = tim->tm_mday;
mo = tim->tm_mon;
yr = tim->tm_year;
if (yr >= 100)
yr -= 100;
}

int main()
{
time_t now = time(0);
Date dt(now);
dt.display();
return 0;
}

[解决办法]
tm_year:year since 1900
tm_mon: month (0 11, 0 = January)
[解决办法]
这是tm结构体的范围
Member Meaning Range
tm_sec seconds after the minute 0-61
tm_min minutes after the hour 0-59
tm_hour hours since midnight 0-23
tm_mday day of the month 1-31
tm_mon months since January 0-11
tm_year years since 1900
tm_wday days since Sunday 0-6
tm_yday days since January 1 0-365
tm_isdst Daylight Saving Time flag

月份是0-11, 所以你要+1才是实际的月份
年份是-1900之后的值,现在2012 ,减去1900 112,因为你有个y-=100,所以最后得到12.

读书人网 >C++

热点推荐