c语言怎么求任意两个日期之间的天数

1121
2023/12/12 7:00:30
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

可以使用以下步骤来求任意两个日期之间的天数:

  1. 从用户输入或其他方式获取两个日期的年份、月份和日期。
  2. 计算每个日期距离公元元年(即元年1月1日)的天数,可以使用下面的公式: 总天数 = (年份 - 1) * 365 + (年份 - 1) / 4 - (年份 - 1) / 100 + (年份 - 1) / 400 + 当年天数 其中,当年天数 = 当月之前的天数 + 当月的天数,当月之前的天数可以使用数组或switch语句来计算。 注意:在使用这个公式计算之前,需要判断年份是否为闰年,闰年的判断条件是年份能被4整除但不能被100整除,或者能被400整除。
  3. 将第二个日期的总天数减去第一个日期的总天数,即可得到任意两个日期之间的天数。

下面是一个示例代码:

#include <stdio.h>

int isLeapYear(int year) {
    if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
        return 1;
    } else {
        return 0;
    }
}

int getDaysOfMonth(int year, int month) {
    int days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year)) {
        return 29;
    } else {
        return days[month - 1];
    }
}

int getTotalDays(int year, int month, int day) {
    int totalDays = (year - 1) * 365 + (year - 1) / 4 - (year - 1) / 100 + (year - 1) / 400;
    for (int i = 1; i < month; i++) {
        totalDays += getDaysOfMonth(year, i);
    }
    totalDays += day;
    return totalDays;
}

int main() {
    int year1, month1, day1;
    int year2, month2, day2;
    printf("请输入第一个日期(年 月 日):");
    scanf("%d %d %d", &year1, &month1, &day1);
    printf("请输入第二个日期(年 月 日):");
    scanf("%d %d %d", &year2, &month2, &day2);
    int totalDays1 = getTotalDays(year1, month1, day1);
    int totalDays2 = getTotalDays(year2, month2, day2);
    int days = totalDays2 - totalDays1;
    printf("两个日期之间的天数为:%d\n", days);
    return 0;
}

希望对你有帮助!

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: c语言从键盘获取字符串的方法是什么