2022年25月1用C语言写相差多少月,余多少天
时间: 2024-06-12 09:06:45 浏览: 18
C语言代码:
```
#include <stdio.h>
int main() {
int year1, month1, day1, year2, month2, day2;
int days_in_month[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int total_days1, total_days2, days_diff, months_diff, years_diff, remainder_days;
printf("请输入第一个日期(yyyy mm dd):");
scanf("%d %d %d", &year1, &month1, &day1);
printf("请输入第二个日期(yyyy mm dd):");
scanf("%d %d %d", &year2, &month2, &day2);
// 计算两个日期距离公元元年1月1日的总天数
total_days1 = year1 * 365 + (year1 - 1) / 4 - (year1 - 1) / 100 + (year1 - 1) / 400;
total_days2 = year2 * 365 + (year2 - 1) / 4 - (year2 - 1) / 100 + (year2 - 1) / 400;
for (int i = 0; i < month1 - 1; i++) {
total_days1 += days_in_month[i];
}
if (month1 > 2 && (year1 % 4 == 0 && year1 % 100 != 0 || year1 % 400 == 0)) {
total_days1 += 1;
}
total_days1 += day1;
for (int i = 0; i < month2 - 1; i++) {
total_days2 += days_in_month[i];
}
if (month2 > 2 && (year2 % 4 == 0 && year2 % 100 != 0 || year2 % 400 == 0)) {
total_days2 += 1;
}
total_days2 += day2;
// 计算相差的总天数、月数、年数和余数天数
days_diff = total_days2 - total_days1;
years_diff = days_diff / 365;
months_diff = (days_diff % 365) / 30;
remainder_days = days_diff - years_diff * 365 - months_diff * 30;
printf("相差 %d 年 %d 月 %d 天", years_diff, months_diff, remainder_days);
return 0;
}
```
注意事项:
1. 代码中假设每个月都是30天,因此计算的月数可能会有些误差,但相差不会太大。
2. 闰年的判断使用了公历规则,即能被4整除但不能被100整除,或者能被400整除的年份为闰年。
相关推荐
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)