C语言:输入一个人的出生年,月,日,再输入当前年,月,日,计算此人的实际年龄。求解各位C语大神。
发布网友
发布时间:2022-09-16 23:45
我来回答
共3个回答
热心网友
时间:2023-10-14 09:37
要利用时间函数,代码如下:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int year,month,day;
printf("input birthday:\n");
scanf("%d %d %d",&year,&month,&day);
time_t cur = time(NULL);
struct tm *today = localtime(&cur);//获得当前的日期
int days0 = year*10000+(month-1)*100+day-1;
int days1 = today->tm_year*10000+(today->tm_mon-1)*100+today->tm_mday-1;
int age = days1-days0;//当日期或者月份不足的时候,会自动从上一级借位,因此计算出的年纪是可靠的,但是月份需要分析:需要减去99加12
int mon = (age-(age/10000)*10000)/100;
printf("age is %dyear %dmonth\n",age/10000,(mon>=12)?(mon-99+12);//计算出年龄
return 0;
}
热心网友
时间:2023-10-14 09:38
/*修改自http://www.jb51.net/article/39907.htm的程序*/
#include <stdio.h>
#define leapyear(year)((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))
int days(int *day1, int *day2)
{
int i=0;
int *tmp;
int diff = 0;
const int month[13]={0,31,28,31,30,31,30,31,31,30,31,30,31};
if(day1[0] == day2[0])
{
if(day1[1] == day2[1])
{
diff = day1[2] - day2[2];
diff = (diff < 0)?(-diff):diff;
}
else
{
if(day1[1] < day2[1])
{
tmp = day1;
day1 = day2;
day2 = tmp;
}
for(i=day2[1]+1; i<day1[1]; i++)
{
diff += month[i];
}
diff += month[day2[1]] - day2[2] + day1[2];
if(day2[1] <= 2 && day1[1] >2)
if(leapyear(day2[0]))
diff++;
}
}
else
{
if(day1[0] < day2[0])
{
tmp = day1;
day1 = day2;
day2 = tmp;
}
for(i=day2[0]+1; i<day1[0]; i++)
{
if(leapyear(i))
diff += 366;
else
diff += 365;
}
for(i=day2[1]+1; i<=12; i++)
{
diff += month[i];
}
diff += (month[day2[1]] - day2[2]);
if(day2[1] <= 2)
if(leapyear(day2[0]))
diff++;
for(i=1; i<day1[1]; i++)
{
diff += month[i];
}
diff += day1[2];
if(day1[1] > 2)
if(leapyear(day1[0]))
diff++;
}
return diff;
}
void main(void)
{
int day1[3], day2[3];
int day = 0;
printf("Input His/Her Birthday\n");
scanf("%d-%d-%d",&day1[0], &day1[1], &day1[2]);
printf("Input Current Date\n");
scanf("%d-%d-%d",&day2[0], &day2[1], &day2[2]);
day=days(day1, day2);
printf("His/Her age is %2.2f\n" , (float)day/365);
getch();
}
热心网友
时间:2023-10-14 09:38
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int age, byear, bmonth, bday, nyear, nmonth, nday;
printf("Please input the birthday(XXXX,XX,XX):");
scanf("%d,%d,%d", &byear, &bmonth, &bday);
printf("/nPlease input now date(XXXX,XX,XX):");
scanf("%d,%d,%d", &nyear, &nmonth, &nday);
age = nyear - byear;
if (nmonth > bmonth)
age++;
else if (nmonth == bmonth)
if (nday > bday)
age++;
printf("/nAge is %d/n", age);
}