12.23 计算日期差,花的时间不短

发布于 2024-12-23  54 次阅读


#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>

typedef struct data {
	int year;
	int month;
	int day;
}data;

//判断是否是闰年
int run(int year) {
	if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
		return 1;
	}
	else return 0;
}

//判断这个月有多少天(参数还有闰年的判断)
int tian(int month,int run) {
	if (month == 2) {
		if (run == 1)return 29;
		if (run == 0)return 28;
	}
	else if (month == 4 || month == 6 || month == 9 || month == 11) {
		return 30;
	}
	else return 31;
}

int main() {
	data start, end;
	scanf("%d%d%d", &start.year, &start.month, &start.day);
	scanf("%d%d%d", &end.year, &end.month, &end.day);
	int sum = 0;
	//特殊情况是同一年
	if (start.year == end.year) {
		for (int i = start.month; i <= end.month; i++) {
			if (i == start.month) {
				sum += tian(i, run(start.year)) - start.day;
			}
			else if (i == end.month) {
				sum += end.day;
			}
			else {
				sum += tian(i, run(start.year));
			}
		}
		printf("%d", sum);
		return 0;
	}
       //如果不是同一年,将跳过上层代码进入下面的代码块
	
       //单独处理start.year的总天数
        for (int i = start.month; i <=12; i++) {
		if (i != start.month) {
			sum += tian(i, run(start.year));
		}
		else {
			sum += tian(i, run(start.year)) - start.day;
		}
	}
        //处理start.year至end.year之间(两者都不含)的总天数
	for (int i = start.year + 1; i < end.year; i++) {
		if (run(i) == 1) {
			sum += 366;
		}
		if (run(i) == 0) {
			sum += 365;
		}
	}
        //单独处理end.year的总天数
	for (int i = 1; i <= end.month; i++) {
		if (i != end.month) {
			sum += tian(i, run(end.year));
		}
		else {
			sum += end.day;
		}
	}
	printf("%d", sum);
	return 0;
}
届ける言葉を今は育ててる
最后更新于 2024-12-23