c++ - 为什么我的年龄错误
问题描述
基本上只是为自己做一个项目。基本上是写一个简单的程序来显示你的年龄和星座。我正在显示我想要的输出,但年龄是错误的。我试图找出原因。我在想,因为我要减去年份。
我的生日是 1991 年 7 月 14 日
它输出我的年龄是 29。我是 28
只是想知道我怎么能把七月而不是七月。很确定我将不得不为星座做很多 if 和 then 语句。
这是代码
#include <iostream>
#include <ctime>
#include <string>
using namespace std;
struct Customer_info
{
string Customer_Name;
int Customer_Month;
int Customer_Day;
int Customer_Year;
};
int main()
{
Customer_info cust;
cout << "What is your name? And when exactly is your birthday?" << endl;
getline (cin, cust.Customer_Name);
cin >> cust.Customer_Month;
cin >> cust.Customer_Day;
cin >> cust.Customer_Year;
cout << "Your name is " << cust.Customer_Name << " " << "and you were born " << cust.Customer_Month << endl;
time_t now = time(0);
tm *date = localtime(&now);
cout << "The date is " << 1 + date->tm_mon << " / " << date->tm_mday << " / " << 1900 + date->tm_year << endl ;
int age;
age = 1900 + date-> tm_year - cust.Customer_Year;
cout << "Your age is " << age << endl;
return 0;
}
解决方案
通过减去岁数来计算年龄会导致年龄计算错误。在准确计算年龄之前,需要判断月份和日期。
您可以创建一个与月份和数字对应的地图,然后您可以用英文输入月份而不是数字,并在需要时使用该地图获取对应月份的数字。
这是代码:
#include <iostream>
#include <ctime>
#include <string>
#include <map>
using namespace std;
map<string, int> monthMap;
struct Customer_info
{
string Customer_Name;
string Customer_Month;
int Customer_Day;
int Customer_Year;
};
int main()
{
string monthString[12]{ "January" ,"February","March","April","May","June","July","August","September","October","November","December" };
for (int i = 0; i < 12; i++)
{
monthMap.insert(pair<string, int>(monthString[i], i + 1));
}
Customer_info cust;
cout << "What is your name? And when exactly is your birthday?" << endl;
getline(cin, cust.Customer_Name);
cin >> cust.Customer_Month;
cin >> cust.Customer_Day;
cin >> cust.Customer_Year;
cout << "Your name is " << cust.Customer_Name << " " << "and you were born " << cust.Customer_Month << endl;
time_t now = time(0);
tm* date = localtime(&now);
cout << "The date is " << 1 + date->tm_mon << " / " << date->tm_mday << " / " << 1900 + date->tm_year << endl;
int age;
age = 1900 + date->tm_year - cust.Customer_Year;
if (date->tm_mon + 1 < monthMap[cust.Customer_Month] || (date->tm_mon + 1 == monthMap[cust.Customer_Month] && date->tm_mday < cust.Customer_Day))
age--;
cout << "Your age is " << age << endl;
return 0;
}
推荐阅读
- r - igraph - 获取在两个顶点之间形成路径的所有边 - 有更好的解决方案吗?
- mysql - 如何在 TEMPORARY 表上使用多个 IN 条件进行选择?
- python-3.x - Python fonttools:检查字体是否支持多代码点表情符号
- mysql - 订单数据冗余
- spring-boot - spring boot saml dsl 的默认使用者 URL
- php - 为未登录用户保护 .PDF 和 .JPG
- c# - 使用变量作为循环的终点 - C#
- angular - 在 Angular 7 ng build --prod 中不起作用
- javascript - 装饰器不会将属性添加到它正在装饰的类。我如何解决它?
- python - 网页抓取:如何从 html 中提取与与其他标签匹配的关键字相对应的链接,而 url 中没有关键字?