年月日转天数,天数转月日

#include <stdio.h>

//为什么要开大小为13的数组?为了使月份与下标对应。例如一月day_p[1]==31
int day_p[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
int day_r[13] = { 0,31,29,31,30,31,30,31,31,30,31,30,31 };


//年月日转天数 思路:
1,判断润/平年
2,遍历对应的数组,依次把每月的天数相加,直到你输入的月份为止
 例如,你输入的是2007年7月21日,遍历到6月就行了。然后把你输入的天数(21)加上

int Dayfofyear(int year, int month, int day) {
    //判断润年
	int res = 0;
	bool st = false;
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		st = true;
	}

    
	if (st) {
		for (int i = 1; i < month; i++) {
			res = res + day_r[i];
		}
		res += day;
	}
	else {
		for (int i = 1; i < month; i++) {
			res = res + day_p[i];
		}
		res += day;
	}
	return res;
}



//天数转月日 思路:
1,判断润年,遍历对应的数组
2,依次遍历月份数组,直到你的天数总和(res) > yearday。
   这时就说明你天数加多了,需要倒退。
   所以要 month--

举个例子,模拟一下。假如你输入的是 2009 209
1,这个是平年,使用对应的数组。 总天数res=0

遍历一月i=1,res=res+[1]=31,i++
遍历二月i=2,res=res+[2]=31+28=59,i++
遍历三月i=3,res=res+[3]=59+31=90,i++
遍历四月i=4,res=res+[4]=90+30=120,i++
遍历五月i=5,res=res+[5]=120+31=151,i++
遍历六月i=6,res=res+[6]=151+30=181,i++
遍历七月i=7,res=res+[7]=181+31=212,i++
这时res=212>209。说明肯定是处于7月份的,因为当1~~7月总天数为212天
但现在i==8,所以回退月份i--
然后把多加上的天数减去,res=res-[7]=212-31=181
1~~6月总天数为181天,所以咱们处于7月份,第209-181=28天









void MonthDay(int year, int yearday) {
	int res = 0;
	bool st = false;
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		st = true;
	}


	int month = 1,day;
	if (st) {
		while (res < yearday) {
			res = res + day_r[month];
			month++;
		}
		month--;
		res -= day_r[month];
		day = yearday - res;
	}
	else {
		while (res < yearday) {
			res = res + day_p[month];
			month++;
		}
		month--;
		res -= day_p[month];
		day = yearday - res;
	}
}

int main() {
    //输入输出自己搞
	return 0;
}

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值