用c语言编写同一年两个日期相差天数
时间: 2023-11-30 17:03:24 浏览: 83
Java判断两个日期相差天数的方法
以下是使用C语言编写的同一年两个日期相差天数的程序:
```c
#include <stdio.h>
int main() {
int year, month1, day1, month2, day2;
int days_in_month[] = {0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
int total_days = 0;
printf("Enter year: ");
scanf("%d", &year);
printf("Enter first date (mm dd): ");
scanf("%d %d", &month1, &day1);
printf("Enter second date (mm dd): ");
scanf("%d %d", &month2, &day2);
// Check for leap year
if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
days_in_month[2] = 29;
}
// Calculate days between dates
if (month1 == month2) {
total_days = day2 - day1;
} else {
total_days += days_in_month[month1] - day1;
for (int i = month1 + 1; i < month2; i++) {
total_days += days_in_month[i];
}
total_days += day2;
}
printf("Total days between dates: %d\n", total_days);
return 0;
}
```
该程序首先要求用户输入年份以及两个日期,然后检查是否为闰年,并使用每个月的天数数组来计算两个日期之间的天数差异。最后,程序将结果输出到控制台。
阅读全文