计算从出生年到现在的天数(假设出生日期是*年1月1日)
代码如下:
AgeToDay.cpp
/*AgeToDay.cpp -- 把自己的年龄转换成天数*/ #include<stdio.h> #include<time.h> #include<stdlib.h> #define RUNYEAR 366 //闰年天数 #define PINGYEAR 365 //平年天数 int getThisYear(); //得到当前年份 char year[]表示指向char类型的指针 bool isRunYear(int year); //判断是否是闰年 int getDays(int year,int age,int days); //得到天数 int getNowDays(); //得到今天是今年的第几天 int main(void) { int year; //今年 int myAge; //年龄 int days; //得到今天是今年的第几天 int allDays; year = getThisYear(); //得到当前年份 days = getNowDays(); printf("Please enter your age:"); if(scanf("%d",&myAge) == 1 && myAge > 0 && myAge < 150) { allDays = getDays(year,myAge,days); printf("the days you have gone is : %d\n",allDays); } else { printf("输入格式错误!\n"); } return 0; } //得到当前系统年份 int getThisYear() { struct tm *nowtime; //时间结构 time_t local_time; //本地时间 char year[5]; //今年 local_time = time(NULL); nowtime = localtime(&local_time); strftime(year,5,"%Y",nowtime); //转换成2001形式 return atoi(year); } int getNowDays() { struct tm *nowtime; time_t local_time; char days[10]; local_time = time(NULL); nowtime = localtime(&local_time); strftime(days,10,"%j",nowtime); puts(days); return atoi(days); } //判断某年是否为闰年,若是则返回true bool isRunYear(int year) { if((year % 4 ==0 && year % 100 !=0) || year % 400 == 0) return true; return false; } //得到从出生年到现在的天数(假设是1月1号出生) int getDays(int year,int age,int days) { int count = 0; //从当前年份到出生年份含有的闰年数 int alldays; for(int i = year -1; i < year - age ; i-- ) { if(isRunYear(i)) count++; } alldays = RUNYEAR * count +PINGYEAR * (age - 1 - count) + days; return alldays; }