询问用户的出生年份并计算他们在当年的年龄。
代码一
#include <stdio.h>
#define CURRENTYEAR 2023
int main()
{
int yearBorn, age;
printf("What year were you born?\n");
scanf(" %d", &yearBorn);
if (yearBorn > CURRENTYEAR){
printf("wrong input!\n");
printf("What year were you born?\n");
scanf(" %d", &yearBorn);
}
age = CURRENTYEAR - yearBorn;
printf("\nSo this year you will turn %d on your birthday!\n",age);
if ((yearBorn % 4) == 0){
printf("\nYou were born in a Leap Year--cool!\n");
}
return 0;
}
代码二
输入当前日期,生日 计算你现在年龄
#include<stdio.h>
int main()
{
int y0,m0,d0;
int y1,m1,d1;
int y,m,d;
printf("请输入学生的生日(年:y0.月:m0.日:d0)\n");
printf("请输入当前日期(年:y0.月:m0.日:d0)\n");
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("请输入生日(包含年月日,请用空格隔开):\n");
scanf_s("%d %d %d", &year, &month, &day);
printf("请输入当前日期(包含年月日,请用空格隔开):\n");
scanf_s("%d %d %d", &newyear, &newmonth, &newday);
wang = newyear - year; //用当前年份减去出生年份,并赋值给wang
if (newmonth - month > 0) { //如果出生月份大于当前月份,则直接输出
printf("当前年龄为:\n");
printf("%d\n", wang);
}
else {
if (newmonth - month == 0) { //如果月份相减等于0,则执行日的判断
if (newday >= day) { //如果当前日大于出生的日,则输出
printf("当前年龄为:\n");
printf("%d\n", wang);
}
else {
printf("当前年龄为:\n");
printf("%d\n", wang - 1); //如果日期相减条件为假,则wang减去1
}
}
else {
printf("当前年龄为:\n");
printf("%d\n", wang - 1); //如果月份相减条件为假,则wang减去1
}
}
return 0;
}
到此这篇关于c语言根据用户输入的出生年份并计算出当前年龄的文章就介绍到这了,更多相关c语言计算年龄内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!