下学期第三周实验报告3.2

实验目的:设计一个DateTime类,显示相应的日期。
实验代码:
#include <iostream>

using namespace std;

class DateTime
{
public:
	void set_DateTime();
	void show_DateTime();
private:
	bool is_DateTime(int, int, int);
	int year;
	int month;
	int day;
};

int main()
{
	DateTime d1;
	DateTime &d2 = d1;
	d1.set_DateTime();
	d2.show_DateTime();

	return 0;
}

void DateTime::set_DateTime()
{
	char c1, c2;
	cout << "请输入日期(格式yy:mm:dd)";
	while(1)
	{
		cin >> year >> c1 >> month >> c2 >> day;
		if(c1 != ':' || c2 != ':')
			cout << "格式不正确,请重新输入" << endl;
		else if(!is_DateTime(year, month, day))
			cout << "时间非法,请重新输入" << endl;
		else
			break;
	}
}

void DateTime::show_DateTime()
{
	cout << year << ":" << month << ":" << day << endl;
}

bool DateTime::is_DateTime(int y, int m, int d)
{
	if(y < 0 || m <= 0 || m > 12)
		return false;
	else if((y % 4 == 0 && y % 100 !=0) || y % 400 == 0)
	{
		if(m == 2 && (d <=0 || d > 29))
			return false;
	}
	else if(m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12)
	{
		if(d <= 0 || d > 31)
			return false;
	}
	else if(m == 2 && (d <= 0 || d > 28))
		return false;
	else if(d <=0 || d > 30)
		return false;
	return true;
}

实验结果代码:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值