c++ - 为什么我年龄不正确

标签 c++ visual-studio datetime ctime

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

我的生日是1991年4月14日

输出我的年龄是29。我是28

只是想知道如何将7月改为7。
可以肯定的是,我将不得不为星座做大量的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;

}

最佳答案

为了显示月份,您需要将所有月份的名称存储在某个位置(最好存储在数组中),然后再引用它(例如,一月将是array [0],八月将是array [7]等,通常它是array [月-1](如果您按正确的顺序排列它们)

年龄问题...我并没有真正理解“错误”的意思,但我想您认为他们有时是错误的,因为您没有检查给定的人今年是否已经过生日(您需要比较当前时间和用户输入的月数和天数,并根据该数字减去年龄(不算年龄)。

关于c++ - 为什么我年龄不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61724047/

相关文章:

sql - 计算每天两个日期时间字段之间的平均时差

c++ - 无法调试 C++ 项目,因为无法静态库启动程序 *.lib

c++ - Qt 调试器输入不工作

c++ - Visual Studio 2010/2012 插件项目问题

c++ - 由于比较器,Visual C++ 抛出映射异常

VB.NET 仅获取日期中的年份

php - 如何在PHP中显示日期范围

c++ - 在 Qt 中为形状设置适当的颜色

c++ - Qt - 没有匹配的调用函数?

c++ - 为什么探查器需要管理权限(在 Windows 上)