C 把年龄转换为天数

计算从出生年到现在的天数(假设出生日期是*年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;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值