首页 > 解决方案 > 为什么我的年龄错误

问题描述

基本上只是为自己做一个项目。基本上是写一个简单的程序来显示你的年龄和星座。我正在显示我想要的输出,但年龄是错误的。我试图找出原因。我在想,因为我要减去年份。

我的生日是 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;

}

标签: c++visual-studiodatetimectime

解决方案


通过减去岁数来计算年龄会导致年龄计算错误。在准确计算年龄之前,需要判断月份和日期。

您可以创建一个与月份和数字对应的地图,然后您可以用英文输入月份而不是数字,并在需要时使用该地图获取对应月份的数字。

这是代码:

#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;
}

在此处输入图像描述


推荐阅读