如何用C语言编写一个求年龄的程序

知道出生年月日和当前的年月日,用C编写一个程序求出当前的年龄,年龄要精确到日。即多少岁零几个月几日,会的帮帮忙,谢谢。

//帮你搞了一个,刚有点小错误,修正了一下
#include"stdio.h"
#include"math.h"

typedef struct
{
int year;
int month;
int day;
}Date;

int date[2][12]={{31,28,31,30,31,30,31,31,30,31,30,31},{31,29,31,30,31,30,31,31,30,31,30,31}};

int judge(int year) //判断是否为闰年//
{
int flag=0;
if((year%4==0&&year%100!=0)||year%400==0) flag=1;
else flag=0;
return flag;
}

Date work(Date user[2]) //计算两个日期相差//
{
Date rec,tmpdate;
if(user[1].month>user[0].month||(user[1].month==user[0].month&&user[1].day>=user[0].day))
rec.year=user[1].year-user[0].year;
else
rec.year=user[1].year-user[0].year-1;
tmpdate.year=user[0].year+rec.year;
tmpdate.month=user[0].month;
tmpdate.day=user[0].day;
int m=judge(user[1].year);
if(tmpdate.year<user[1].year)
{
if(tmpdate.day<= user[1].day)
{
rec.month= 12-tmpdate.month+user[1].month;
rec.day= user[1].day-tmpdate.day;
}
else
{
rec.month= 11-tmpdate.month+user[1].month;
rec.day=date[m][user[1].month]-tmpdate.day+ user[1].day;
}
}
else
{
if(tmpdate.day<= user[1].day)
{
rec.month= user[1].month-user[0].month;
rec.day= user[1].day-tmpdate.day;
}
else
{
rec.month= user[1].month-1;
rec.day=date[m][user[1].month]-tmpdate.day+ user[1].day;
}
}
return rec;

}

int main()
{
Date user[2];
int i;
printf("Please input 2 dates(such as 2008.10.2).\n");
for(i=0;i<2;i++)
{
scanf("%d.%d.%d",&user[i].year,&user[i].month,&user[i].day);
}
Date d=work(user);
printf("There are %d years %d month %d days.\n",d.year,d.month,d.day);
getchar();
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-04-30
#include <time.h>
#include <stdio.h>
#include <string.h>

#ifdef _DEBUG
void printTm(struct tm *t)
{
printf("===========================\n");
printf("tm_year = %d\n", t->tm_hour);
printf("tm_year = %d\n", t->tm_isdst);
printf("tm_year = %d\n", t->tm_mday);
printf("tm_year = %d\n", t->tm_min);
printf("tm_year = %d\n", t->tm_mon);
printf("tm_year = %d\n", t->tm_sec);
printf("tm_year = %d\n", t->tm_year);
printf("===========================\n");
}
#endif

int main()
{
time_t ltime;
struct tm *today;
struct tm *minus;
struct tm birthday;
long l;

time(<ime);
today = localtime(<ime);
today->tm_hour = today->tm_min = today->tm_sec = 0;

memset(&birthday, 0, sizeof(struct tm));
printf("Input birthday like year-month-day:\n");
scanf("%d-%d-%d",&birthday.tm_year, &birthday.tm_mon, &birthday.tm_mday);
birthday.tm_year -= 1900;
birthday.tm_mon -= 1;
#ifdef _DEBUG
printTm(&birthday);
printTm(today);
#endif
l = mktime(today) - mktime(&birthday);
minus = gmtime(&l);
printf("%d years %d monthes %d days\n", minus->tm_year - 70, minus->tm_mon, minus->tm_mday);

return 0;
}

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网