C语言实现秒级计数并打印日期信息

本文将展示如何使用C语言实现一个程序,该程序能够每秒递增一次计数,并通过printf函数打印计数对应的年、月、日、星期。我们以2020年为例,从1月1日开始计数,并考虑了闰年情况。

代码示例

#include <stdio.h>
#include <unistd.h> // 为了使用 sleep 函数

// 判断某年是否为闰年
int isLeapYear(int year) {
    return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}

// 获取某月的天数
int getDaysInMonth(int year, int month) {
    int daysInMonth[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
    if (month == 2 && isLeapYear(year)) {
        return 29;
    }
    return daysInMonth[month - 1];
}

// 获取某年的天数
int getDaysInYear(int year) {
    return isLeapYear(year) ? 366 : 365;
}

// 获取某日期对应的年、月、日、星期
void getDateInfo(int count, int *year, int *month, int *day, int *weekday) {
    *year = 2020;
    int days = count - 1;
    while (days >= getDaysInYear(*year)) {
        days -= getDaysInYear(*year);
        (*year)++;
    }
    *month = 1;
    while (days >= getDaysInMonth(*year, *month)) {
        days -= getDaysInMonth(*year, *month);
        (*month)++;
    }
    *day = days + 1;
    *weekday = (count + 2) % 7;  // 2020年1月1日是星期三,计算星期几的方法
}

int main() {
    int count = 10;  // 初始计数为10
    int year, month, day, weekday;

    while (count <= 366) {
        getDateInfo(count, &year, &month, &day, &weekday);
        printf('%d年%d月%d日-星期', year, month, day);
        switch (weekday) {
            case 0: printf('日\n'); break;
            case 1: printf('一\n'); break;
            case 2: printf('二\n'); break;
            case 3: printf('三\n'); break;
            case 4: printf('四\n'); break;
            case 5: printf('五\n'); break;
            case 6: printf('六\n'); break;
        }
        count++;
        sleep(1);  // 等待1秒
    }

    return 0;
}

代码解释

  1. 头文件: #include <stdio.h> 用于标准输入输出, #include <unistd.h> 用于 sleep 函数,使程序暂停一秒。
  2. 闰年判断: isLeapYear 函数用于判断年份是否为闰年。
  3. 获取月天数: getDaysInMonth 函数用于获取指定年份和月份的天数。
  4. 获取年天数: getDaysInYear 函数用于获取指定年份的天数。
  5. 获取日期信息: getDateInfo 函数根据计数 count 获取对应的年、月、日和星期。
  6. 主函数: main 函数中,设置初始计数为10,循环遍历计数,每秒递增一次,并调用 getDateInfo 函数获取日期信息,最后使用 printf 函数打印日期信息。

运行结果

运行上述代码,程序将会每秒打印一次计数对应的年、月、日、星期,例如:

2020年1月10日-星期五
2020年1月11日-星期六
2020年1月12日-星期日
...

总结

本文介绍了如何使用C语言实现秒级计数,并通过printf函数打印计数对应的日期信息。代码示例以2020年为例,从1月1日开始计数,并考虑了闰年情况。你可以根据需要修改代码,实现不同的计数范围和起始日期。


原文地址: https://www.cveoy.top/t/topic/pbNW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录