帮我写一个计算我在2023年2月3日的年龄的c++程序要求输入我的生日输出今天的日期、我的周岁与虚岁
以下是一个计算年龄的C++程序,输入出生日期和今天的日期即可计算周岁和虚岁:
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
int birthYear, birthMonth, birthDay;
int todayYear, todayMonth, todayDay;
int age, virtualAge;
// 输入出生日期
cout << "请输入出生年份: ";
cin >> birthYear;
cout << "请输入出生月份: ";
cin >> birthMonth;
cout << "请输入出生日期: ";
cin >> birthDay;
// 获取今天的日期
time_t t = time(NULL);
tm* now = localtime(&t);
todayYear = now->tm_year + 1900;
todayMonth = now->tm_mon + 1;
todayDay = now->tm_mday;
// 计算周岁
age = todayYear - birthYear;
if (todayMonth < birthMonth || (todayMonth == birthMonth && todayDay < birthDay)) {
age--;
}
// 计算虚岁
virtualAge = age + 1;
// 输出结果
cout << "今天的日期是: " << todayYear << "年" << todayMonth << "月" << todayDay << "日" << endl;
cout << "你的周岁是: " << age << endl;
cout << "你的虚岁是: " << virtualAge << endl;
return 0;
}
注意,这个程序假设输入的出生日期是合法的,没有进行输入验证。如果需要更加严谨的程序,需要进行输入验证和错误处理。
原文地址: https://www.cveoy.top/t/topic/q7W 著作权归作者所有。请勿转载和采集!