**
实现了一个小程序,实现根据出生日期计算年龄
**
这里没有考虑如果出生年为闰年,或者当前年为闰年时出生日期为二月的情况
如果需要考虑,那么计算前加入一个闰年判断,并且根据是否闰年在计算时调用不同的monthday数组即可。
我们在这里默认为不是闰年。
并且我们认为出生第一天为1.
界面如下
测试
全部代码:
#include <iostream>
using namespace std;
class base
{
public:
int m_year = 0;
int m_month = 0;
int m_day = 0;
};
bool Check(int year, int month, int day)//检查函数,检查月份以及输入天数是否合法,返回true or false
{
if (month > 0 && month <= 12)
{
if (month == 2 && day <= 29) { return true; }
else if (month != 2 && day > 0 && day <= 31)
{
return true;
}
else { return false; }
}
else return false;
}
int main()
{
base b;//创建一个过去的时间类
base bNow;//现在时间类
int year = 0;//这三个是最后输出的年龄,精确到日
int month = 0;
int day = 0;
//创建一个每个月天数的数组,将二月考虑为29天
int monthday[12] = { 31,28,31,30,31,30,31,31,30,31,30,31 };
int select;
while (true)
{ //菜单
cout << "***********************************" << endl;
cout << "********* [1] 计算年龄 ************" << endl;
cout << "********* [2] 退出系统 ************" << endl;
cout << "***********************************" << endl;
cout << endl;
cout << "请选择要使用的功能:" << endl;
cin >> select;
switch (select)
{
case 1://计算年龄的实现
{
cout << "请输入您的出生日期,年 月 日,用空格隔开" << endl;
cin >> b.m_year >> b.m_month >> b.m_day;
cout << "请输入现在的日期,年 月 日,用空格隔开" << endl;
cin >> bNow.m_year >> bNow.m_month >> bNow.m_day;
cout << endl;
if (Check(b.m_year, b.m_month, b.m_day) && Check(bNow.m_year, bNow.m_month, bNow.m_day))
{
if (bNow.m_month > b.m_month)
{
if (bNow.m_day < b.m_day)
{
year = bNow.m_year - b.m_year;
month = bNow.m_month - b.m_month - 1;
day = monthday[b.m_month - 1] - b.m_day + bNow.m_day + 1;
}
else
{
year = bNow.m_year - b.m_year;
month = bNow.m_month - b.m_month;
day = bNow.m_day - b.m_day + 1;
}
}
else if (bNow.m_month < b.m_month)
{
if (bNow.m_day < b.m_day)
{
year = bNow.m_year - b.m_year - 1;
month = 12 - b.m_month + bNow.m_month - 1;
day = monthday[b.m_month - 1] - b.m_day + bNow.m_day + 1;
}
else
{
year = bNow.m_year - b.m_year - 1;
month = 12 - b.m_month + bNow.m_month;
day = bNow.m_day - b.m_day + 1;
}
}
else //if (bNow.m_month == b.m_month)
{
if (bNow.m_day < b.m_day)
{
year = bNow.m_year - b.m_year - 1;
month = 12 - b.m_month + bNow.m_month - 1;
day = monthday[b.m_month - 1] - b.m_day + bNow.m_day + 1;
}
else
{
year = bNow.m_year - b.m_year;
month = bNow.m_month - b.m_month;
day = bNow.m_day - b.m_day + 1;
}
}
}
else
{
cout << "非法数据请重输入" << endl;
system("pause");
return 0;
}
cout << "您的年龄为:" << year << "岁 " << month << "月 " << day << "天" << endl;
cout << endl;
system("pause");
system("cls");//清屏
}
break;
case 2:
system("pause");
return 0;
break;
default:
break;
}
}
}