C语言 计算年龄,给定的出生日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2677396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:14:23  来源:igfitidea点击:

Calculate Age, Given Date of Birth

c

提问by bond

Given a date of birth, how would I go about calculating an age in C?

给定出生日期,我将如何计算 C 中的年龄?

For example, if today's date is 20/04/2010 and the date of birth given is 12/08/86, then age will be 23 years, 8 months, and 8 days.

例如,如果今天的日期是 20/04/2010,给出的出生日期是 12/08/86,那么年龄将为 23 岁 8 个月零 8 天。

Any suggestions would be appreciated. Thanks!

任何建议,将不胜感激。谢谢!

回答by RJFalconer

For just the year (no months/days) :

仅一年(无月/日):

1) Format the dates to yyyymmdd

1) 将日期格式化为 yyyymmdd

2) Subtract the date of birth from date

2) 用日期减去出生日期

3) Remove the last 4 numbers

3) 删除最后 4 个数字

(Language agnostic)

(语言不可知论者)



So for your example;

所以对于你的例子;

date 20/04/2010
birth 12/08/1986

convert

转变

date 20100420
birth 19860812

subtract

减去

20100420-19860812 = 239608

drop last 4 digits

去掉最后 4 位数字

23

回答by caf

The way to approach a problem like this is to figure out how you'd do it using a pencil and paper - then formalise that into a program.

解决此类问题的方法是弄清楚如何使用铅笔和纸来解决问题 - 然后将其形式化为程序。

For this particular problem, that means at a high level, "subtract birth date from current date". For this subtraction, you use a variation of the same algorithm you learn for subtraction in primary school - where you start by subtracting the lower value column (in this case, "days"), borrowing from the next-higher-value column if necessary. For example, to subtract 1986-09-15 from 2010-04-10, you would do:

对于这个特定问题,这意味着在高层次上,“从当前日期减去出生日期”。对于此减法,您​​使用在小学学习减法的相同算法的变体 - 您首先减去较低值的列(在本例中为“天”),如有必要,从下一个较高值的列中借用. 例如,要从 2010-04-10 中减去 1986-09-15,您可以执行以下操作:

2010-04-10 -
1986-09-15
----------

10 is less than 15, so you have to borrow from the months column. This means that the months column goes down by one (to 3), and the days column goes up by the number of days in month 3 (March - so 31). You can now do the subtraction of the days column:

10 小于 15,因此您必须从月列中借用。这意味着月份列减少了 1(到 3),而天数列增加了第 3 个月(3 月 - 31 日)的天数。您现在可以减去天数列:

2010-03-41 -
1986-09-15
----------
       -26

We can now move on to the months column. 3 is less than 9, so we have to borrow again, this time from the year. Take one off the year, and add 12 to the month (since there are always 12 months in a year), then perform the subtraction:

我们现在可以转到月列。3 小于 9,所以我们必须再次借用,这次是从年份开始。从年份中减去一个,然后将月份加 12(因为一年中总是有 12 个月),然后执行减法:

2009-15-41 -
1986-09-15
----------
    -06-26

We can now work on the years - there's never a need to borrow here (unless you're trying to calculate the age of someone born in the future!):

我们现在可以计算年份 - 永远不需要在这里借用(除非您正在尝试计算未来出生的人的年龄!):

2009-15-41 -
1986-09-15
----------
  23-06-26

This means the difference is 23 years, 6 months, 26 days.

这意味着差异是23年6个月26天。

You can now work on turning this into a program (hint: use three seperate integer variables for years, months and days). The trickiest part is the borrow from the months column - you need to know how many days are in that month, including leap years for February.

您现在可以将其转换为程序(提示:使用三个单独的整数变量表示年、月和日)。最棘手的部分是从月份列中借用 - 您需要知道该月有多少天,包括 2 月份的闰年。

回答by Uri

I'm assuming, based on your description, that you have to print out the full difference, not just years.

我假设,根据您的描述,您必须打印出完整的差异,而不仅仅是年。

One part of the problem is to input the dates correctly and break them down into components, I'll assume you already know how to do that or got sample code for that.

问题的一部分是正确输入日期并将它们分解为组件,我假设您已经知道如何执行此操作或已获得示例代码。

What you need to do now is to calculate the difference. One way to do this would be to pick a reference date (e.g., Jan 1st 1900), and calculate how many days it had been until the first date and the second date, and calculate the difference in days. Then you take the difference in days and break it back into years/months/days.

您现在需要做的是计算差异。一种方法是选择一个参考日期(例如,1900 年 1 月 1 日),并计算距第一个日期和第二个日期已经过了多少天,并计算天数差异。然后你把天数的差异分解成年/月/天。

Two things to notice are:

需要注意的两点是:

1) Take leap years into account.

1) 考虑闰年。

2) Figure out how to translate a number of dates into months, since each month has a different number of days.

2) 弄清楚如何将多个日期转换为月份,因为每个月都有不同的天数。

3) If you had to input times and not just dates, you could be off by a day. Similarly if time zones are input.

3)如果你必须输入时间而不仅仅是日期,你可能会休息一天。同样,如果输入时区。

I would check with the instructor whether you can make a simplifying assumption about that (E.g., months are always 30, leap years are ignored, etc.). I find it hard to believe that a homework assignment would require you to deal with these correctly.

我会与讲师核实您是否可以对此做出简化假设(例如,月份始终为 30,闰年被忽略等)。我发现很难相信家庭作业会要求您正确处理这些问题。

回答by Matthew Flaschen

If you're allowed to use the libraries, it's not too hard. Look at strptime, struct tm, time, and localtime. Once you have it in "broken-down" form (struct tm), it's easy to compute the difference (look at tm_yday, tm_mon, and tm_yday).

如果您被允许使用这些库,那并不太难。查看strptimestruct tmtimelocaltime。一旦你把它变成“分解”形式 ( struct tm),就很容易计算出差异(看看tm_ydaytm_mon、 和tm_yday)。

回答by duffymo

If today's date falls after the birthday, the age is the difference between the birth year and today's year. If today's date falls before the birthday, subtract 1.

如果今天的日期在生日之后,则年龄是出生年份与今天年份之间的差值。如果今天的日期在生日之前,则减去 1。

回答by nitin

/* program for calculating the age */
/* author - nitin kumar pandey */
/* mail - [email protected] */ 
#include<stdio.h>
#include<conio.h>
int d1,d2,d3,m1,m2,m3,y1,y2,y3;
void year(int d1,int m1,int y1,int d2,int m2,int y2);
void main()
{
clrscr();
printf("please enter the current date \n");
printf("enter the day");
scanf("%d",&d1);
printf("enter the month");
scanf("%d",&m1);
printf("enter the year");
scanf("%d",&y1);
printf("Now thank you for your cooperation \n now please enter the date of birth");
printf("enter the day");
scanf("%d",&d2);
printf("enter the month");
scanf("%d",&m2);
printf("enter the year");
scanf("%d",&y2);
year(d1,m1,y1,d2,m2,y2);
getch();
}

void year(int d1,int m1,int y1,int d2,int m2,int y2)
{
    if(d2>d1)
    {
    m1=m1-1;
    d1=d1+30;
    }
    if(m2>m1)
    {
    y1=y1-1;
    m1=m1+12;
    }
    if(y2>y1)
    {
    exit(0);
    }
    d3=d1-d2;
    m3=m1-m2;
    y3=y1-y2;
    printf("current age is \n day %d \n month %d \n year %d ",d3,m3,y3);


}

回答by user2930588

//Age calculation. A simple c++ program  
    #include<iostream>
    #include<iostream>
    #include<ctime>
    using namespace std;
    void main()
    {
        system("cls");
        time_t theTime = time(NULL);
        struct tm *aTime = localtime(&theTime);

        int currentday = aTime->tm_mday;
        int currentmonth = aTime->tm_mon + 1; // Month is 0 - 11, add 1 to get a jan-dec 1-12 concept
        int currentyear = aTime->tm_year + 1900; 



        int birthday,birthmonth,birthyear;
        cout<<"Enter birth year: ";
        cin>>birthyear;

        if(birthyear>currentyear)
        {
            cout<<"Current year: "<<currentyear<<endl
                <<"Birht year  : "<<birthyear<<endl
                <<"Invalid...."<<endl<<endl;
            system("pause");
            main();
        }
        else if(birthyear<1900)
        {
            cout<<"Birht year should greater than 1900...."<<endl;
            system("pause");
            main();
        }
        cout<<"Enter birth month: ";
        cin>>birthmonth;
        if(birthmonth<1 || birthmonth>12)
        {
            cout<<"Birth month should be 1-12"<<endl;
            system("pause");
            main();
        }
        else if(birthyear==currentyear && birthmonth>currentmonth)
        {
            cout<<"Current Month/Year: "<<currentmonth<<"/"<<currentyear<<endl
                <<"Birth Month/Year  : "<<birthmonth<<"/"<<birthyear<<endl
                <<"Future Birth Date. Invalid...."<<endl;
            system("pause");
            main();
        }
        cout<<"Enter birth day: ";
        cin>>birthday;
        if(birthday<1 || birthday>31)
        {
            cout<<"Birth day should 1-31"<<endl;
            system("pause");
            main();
        }
        else if(birthyear==currentyear && birthmonth==currentmonth && birthday>currentday)
        {
            cout<<"Current Day/Month/Year: "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl
                <<"Birth Day/Month/Year  : "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl
                <<"Future Birth Date. Invalid...."<<endl;
            system("pause");
            main();
        }
        else if(birthyear%4==0 && birthmonth==2 && birthday>29)
        {
            cout<<"Febuary should be 1-29"<<endl;
            system("pause");
            main();
        }
        else if( (birthmonth==4 || birthmonth==6 || birthmonth==9 || birthmonth==11) && birthday>31)
        {
            cout<<"This month cannot have 31 days...."<<endl;
            system("pause");
            main();
        }


        int ageday,agemonth,ageyear;


        if(birthmonth>currentmonth)
        {
            agemonth=currentmonth;
            ageyear=currentyear-birthyear-1;
            ageday=currentday;
        }
        else
        {
            agemonth=currentmonth-birthmonth;
            ageyear=currentyear-birthyear;
            ageday=currentday-birthday;
        }

        if(ageyear==0 && agemonth==0)
        {
            cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
            cout<<"Current Date      : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
            cout<<"your Age          : "<<ageday<<" days"<<endl;
        }
        else if(ageyear==0)
        {
            cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
            cout<<"Current Date      : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
            cout<<"your Age          : "<<agemonth<<" Months"<<ageday<<" days"<<endl;
        }
        else if(agemonth==0)
        {
            cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
            cout<<"Current Date      : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
            cout<<"your Age          : "<<ageyear<<" years"<<ageday<<" days"<<endl;
        }
        else if(ageday==0)
        {
            cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
            cout<<"Current Date      : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
            cout<<"your Age          : "<<ageyear<<" years"<<agemonth<<" Months"<<endl;
        }
        else
            cout<<"your Date of Birth: "<<birthday<<"/"<<birthmonth<<"/"<<birthyear<<endl;
            cout<<"Current Date      : "<<currentday<<"/"<<currentmonth<<"/"<<currentyear<<endl;
            cout<<"your Age          : "<<ageyear<<" years"<<agemonth<<" Months"<<ageday<<" days"<<endl;
        system("pause");
    }
//AAW

回答by null programmer

The only issue with this code is that it doesn't factor in if you are born on leap day. there can be another if statement for that though.

此代码的唯一问题是它不会影响您是否出生在闰日。不过,可以有另一个 if 语句。

// Age Calculator

time_t t = time(NULL);
struct tm tm = *localtime(&t);

int num_day;

if ( month == 1 )
{
        num_day = 31;
}
if ( month == 2 )
{
        num_day = 28;
}
if ( month == 3 )
{
        num_day = 31;
}
if ( month == 4 )
{
        num_day = 30;
}
if ( month == 5 )
{
        num_day = 31;
}
if ( month == 6 )
{
        num_day = 30;
}
if ( month == 7 )
{
        num_day = 31;
}
if ( month == 8 )
{
        num_day = 31;
}
if ( month == 9 )
{
        num_day = 30;
}
if ( month == 10 )
{
        num_day = 31;
}
if ( month == 11 )
{
        num_day = 30;
}
if ( month == 12 )
{
        num_day = 31;
}

int age_year = (tm.tm_year + 1900) - year;
int age_month = (tm.tm_mon + 1) - month;
int age_day = (tm.tm_mday) - day;

if ( age_month <= 0 )
{
        age_year = (tm.tm_year + 1900) - year - 1;
        age_month = 12 + (tm.tm_mon + 1) - month;
}

if ( age_day <= 0 )
{
        age_month = 12 + (tm.tm_mon + 1) - month - 1;
        age_day = num_day + (tm.tm_mday) - day;
}

printf("Your age: %d years %d months %d days\n", age_year, age_month, age_day);