这篇文章主要讲解了“c语言如何实现根据用户输入的出生年份并计算出当前年龄”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“c语言如何实现根据用户输入的出生年份并计算出当前年龄”吧!
询问用户的出生年份并计算他们在当年的年龄。
代码一
#include <stdio.h> #define CURRENTYEAR 2023 int main() { int yearBorn, age; printf("What year were you born? "); scanf(" %d", &yearBorn); if (yearBorn > CURRENTYEAR){ printf("wrong input! "); printf("What year were you born? "); scanf(" %d", &yearBorn); } age = CURRENTYEAR - yearBorn; printf(" So this year you will turn %d on your birthday! ",age); if ((yearBorn % 4) == 0){ printf(" You were born in a Leap Year--cool! "); } return 0; }
代码二
输入当前日期,生日 计算你现在年龄
#include<stdio.h> int main() { int y0,m0,d0; int y1,m1,d1; int y,m,d; printf("请输入学生的生日(年:y0.月:m0.日:d0) "); printf("请输入当前日期(年:y0.月:m0.日:d0) "); scanf("%d%d%d",&y0,&m0,&d0); scanf("%d%d%d",&y1,&m1,&d1); if(d1<d0) { m1--;//m1=m1-1,m1-=1 switch(m1) { case 2:d=d1+28-d0;break; case 4:d=d1+30-d0;break; case 6:d=d1+30-d0;break; case 9:d=d1+30-d0;break; case 11:d=d1+30-d0;break; } } else d=d1-d0; if(m1<m0) { y1--; m=m1+12-m0; } else { m=m1-m0; y=y1-y0; } printf("实际年龄为:年=%d,月=%d,日=%d",y,m,d); return 0; }
代码三
输入一个人的出生年月日及当前年月日求那个人现在的年龄,注意平年、闰年的判断。
#include<stdio.h> //定义了三个变量类型、一些宏和各种函数来执行输入和输出 int main() { int year, month, day, newyear, newmonth, newday, wang; //定义出生和当前的年、月、日 printf("请输入生日(包含年月日,请用空格隔开): "); scanf_s("%d %d %d", &year, &month, &day); printf("请输入当前日期(包含年月日,请用空格隔开): "); scanf_s("%d %d %d", &newyear, &newmonth, &newday); wang = newyear - year; //用当前年份减去出生年份,并赋值给wang if (newmonth - month > 0) { //如果出生月份大于当前月份,则直接输出 printf("当前年龄为: "); printf("%d ", wang); } else { if (newmonth - month == 0) { //如果月份相减等于0,则执行日的判断 if (newday >= day) { //如果当前日大于出生的日,则输出 printf("当前年龄为: "); printf("%d ", wang); } else { printf("当前年龄为: "); printf("%d ", wang - 1); //如果日期相减条件为假,则wang减去1 } } else { printf("当前年龄为: "); printf("%d ", wang - 1); //如果月份相减条件为假,则wang减去1 } } return 0; }