用c语言编写数字时钟

img

结果和图片基本一致就行,尽量在编译中补充注释,方便我理解。长度没有限制。
时间需要不断变化,并不是打印时间

有GUI稍显麻烦, 这是CSDN自己的chitgpt代码, 关键词: C语言实现的数字时钟代码 用fltk. 稍作修改.
*
没有倒计时功能, 只是一个简单的时钟显示程序
*
** 不是C语言, 是C++ **,
*
如果只能用C语言,估计比较费事.

#include <FL/Fl.H>
#include <FL/Fl_Box.H>
#include <FL/Fl_Button.H>
#include <FL/Fl_Window.H>
#include <cstdio>
#include <cstdlib>
#include <ctime>

Fl_Window *window;
Fl_Box *clock_box;
Fl_Button *quit_button;

void update_time(void * /*unused*/)
{
    // static int i = 0;
    time_t t = time(nullptr);
    struct tm *tm = localtime(&t);
    static char time_str[32];
    sprintf(time_str, "%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
    clock_box->label(time_str);
    // clock_box->labelfont(0 + i++);
    Fl::repeat_timeout(1.0, update_time);
}

void quit_callback(Fl_Widget * /*unused*/, void * /*unused*/)
{
    window->hide();
}

int main(int argc, char **argv)
{
    window = new Fl_Window(200, 100, "Digital Clock");

    clock_box = new Fl_Box(0, 0, 200, 50, "00:00:00");

    Fl::set_fonts("-*");
    clock_box->align(FL_ALIGN_CENTER | FL_ALIGN_INSIDE);
    clock_box->labelsize(30);
    clock_box->labelfont(16);

    quit_button = new Fl_Button(70, 60, 60, 30, "Quit");

    quit_button->callback(quit_callback);

    window->end();
    window->show(argc, argv);

    Fl::add_timeout(1.0, update_time);

    return Fl::run();
}

如果非要液晶效果, 需要液晶字体, 比如DS-Digital字体, 安装后找到其字体编码, 用 clock_box->labelfont(16);设置即可

以下是一份C语言实现的数字时钟代码的思路,可供参考:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print_current_time();
void set_time();
void count_down();

int main()
{
int choice;
do {
printf("
1.打印当前时间
");
printf("2.修改时间
");
printf("3.倒计时
");
printf("4.退出
");
printf("请选择操作:");
scanf("%d", &choice);

switch (choice) {
case 1:
print_current_time();
break;
case 2:
set_time();
break;
case 3:
count_down();
break;
case 4:
printf("已退出!");
break;
default:
printf("输入有误,请重新选择!");
}
} while (choice != 4);

return 0;
}

void print_current_time()
{
time_t t;
struct tm *cur_time;
t = time(NULL); //获取时间信息
cur_time = localtime(&t); //转换为当地时间

printf("当前时间:%02d:%02d:%02d
", cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec);
}

void set_time()
{
time_t t;
struct tm *new_time;
int hour, minute, second;
printf("请输入新的时间(时 分 秒):");
scanf("%d %d %d", &hour, &minute, &second);

t = time(NULL); //获取时间信息
new_time = localtime(&t); //转换为当地时间

new_time->tm_hour = hour;
new_time->tm_min = minute;
new_time->tm_sec = second;

t = mktime(new_time); //转换回time_t格式
printf("修改成功,当前时间:%02d:%02d:%02d
", new_time->tm_hour, new_time->tm_min, new_time->tm_sec);
}

void count_down()
{
int seconds;
printf("请输入倒计时的时间(秒):");
scanf("%d", &seconds);

while (seconds >= 0) {
printf("倒计时:%02d:%02d:%02d
", seconds/3600, (seconds/60)%60, seconds%60);
seconds--;
sleep(1);
}
printf("倒计时结束!
");
}

代码实现了数字时钟的基本功能:打印当前时间、设置时间和倒计时。其中,打印当前时间和倒计时的逻辑比较简单,直接调用系统时间相关的函数即可。设置时间则需要先获取当前时间,再修改对应的参数,最后转换回time_t格式。在倒计时时,使用sleep函数让程序休眠1秒钟。需要注意的是,本代码仅供参考,实际应用中可能需要加入一些异常处理的逻辑,例如输入的时间是否合法、倒计时中的暂停和取消等。

以下是用C语言编写的数字时钟代码,可以实时显示当前时间,同时可以通过用户输入来修改时间:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print_time(int hour, int minute, int second) {
    printf("%02d:%02d:%02d\n", hour, minute, second);
}

int main() {
    int hour, minute, second;
    time_t current_time;
    struct tm *time_info;
    char time_string[9];
    int choice;

    // 获取当前时间
    time(&current_time);
    time_info = localtime(&current_time);

    hour = time_info->tm_hour;
    minute = time_info->tm_min;
    second = time_info->tm_sec;

    // 显示当前时间
    printf("Current time: ");
    print_time(hour, minute, second);

    // 修改时间
    printf("Do you want to modify the time? (1 for yes, 0 for no) ");
    scanf("%d", &choice);

    if (choice) {
        printf("Enter the new time (in format hour minute second): ");
        scanf("%d %d %d", &hour, &minute, &second);

        // 显示修改后的时间
        printf("New time: ");
        print_time(hour, minute, second);
    }

    return 0;
}
在上面的代码基础上,可以添加倒计时功能,即设置一个倒计时时间,然后每秒钟更新一次显示剩余时间,直到倒计时结束。以下是添加倒计时功能后的代码:

c
Copy
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print_time(int hour, int minute, int second) {
    printf("%02d:%02d:%02d\n", hour, minute, second);
}

int main() {
    int hour, minute, second;
    time_t current_time;
    struct tm *time_info;
    char time_string[9];
    int choice;
    int countdown = 0;

    // 获取当前时间
    time(&current_time);
    time_info = localtime(&current_time);

    hour = time_info->tm_hour;
    minute = time_info->tm_min;
    second = time_info->tm_sec;

    // 显示当前时间
    printf("Current time: ");
    print_time(hour, minute, second);

    // 修改时间或设置倒计时
    printf("Do you want to modify the time or set a countdown? (1 for modify, 2 for countdown, 0 for neither) ");
    scanf("%d", &choice);

    if (choice == 1) {
        printf("Enter the new time (in format hour minute second): ");
        scanf("%d %d %d", &hour, &minute, &second);

        // 显示修改后的时间
        printf("New time: ");
        print_time(hour, minute, second);
    } else if (choice == 2) {
        printf("Enter the countdown time (in seconds): ");
        scanf("%d", &countdown);

        // 显示倒计时时间
        printf("Countdown time: ");
        print_time(0, 0, countdown);

        // 开始倒计时
        while (countdown >= 0) {
            system("clear"); // 清屏
            printf("Countdown time: ");
            print_time(0, 0, countdown);
            sleep(1); // 等待1秒钟
            countdown--;
        }

        printf("Time's up!\n");
    }

    return 0;
}

上面的代码中,通过添加一个倒计时时间的变量countdown来实现倒计时功能。用户选择了倒计时选项后,程序会提示用户输入倒计时时间(单位为秒),然后开始倒计时。在倒计时过程中,程序会每隔1秒钟更新一次剩余时间的显示,并使用system("clear")命令清屏,以实现动态更新显示。倒计时结束后,程序会显示一个提示信息“Time's up!”。

下面是一个简单的数字时钟程序,它可以实时显示当前时间、设置修改时间和倒计时功能。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void print_time(int h, int m, int s) // 输出时间函数
{
    printf("%02d:%02d:%02d\n", h, m, s);
}

int main() 
{
    int h = 0, m = 0, s = 0; // 初始化时、分、秒
    int delay_hours = 0, delay_minutes = 0, delay_seconds = 0; // 初始化倒计时时长
    char option; // 存储用户选项

    while (1) // 主循环
    {
        system("cls"); // 清屏
        printf("当前时间:");
        print_time(h, m, s);

        printf("\n1. 修改时间\n");
        printf("2. 倒计时\n");
        printf("0. 退出\n");
        printf("请输入选项体验:");
        scanf("%c", &option);
    
        switch (option) // 处理用户选项
        {
            case '1': 
            {
                printf("\n请输入新的时间:(格式为时:分:秒)\n");
                scanf("%d:%d:%d", &h, &m, &s);

                if (h >= 24 || m >= 60 || s >= 60) // 输入错误判断
                {
                    printf("\n输入错误,请重新输入!\n");
                    system("pause");
                    break;
                }

                break;
            }
            
            case '2': 
            {
                printf("\n请输入倒计时时长:(格式为时:分:秒)\n");
                scanf("%d:%d:%d", &delay_hours, &delay_minutes, &delay_seconds);
                int delay_time = delay_hours * 3600 + delay_minutes * 60 + delay_seconds;

                if (delay_time <= 0) // 输入错误判断
                {
                    printf("\n输入错误,请重新输入!\n");
                    system("pause");
                    break;
                }

                printf("\n倒计时开始,请稍等...\n");
                while (delay_time > 0) // 倒计时
                {
                    system("cls"); // 清屏
                    printf("倒计时:");
                    print_time(0, 0, delay_time);
                    delay_time--;
                    sleep(1); // 暂停一秒钟
                }

                printf("\n倒计时结束!\n");
                system("pause");
                break;
            }

            case '0': 
            {
                printf("\n感谢使用!");
                return 0;
            }

            default:
            {
                printf("\n输入错误,请重新输入!\n");
                system("pause");
                break;
            }
        }
    }
}

运行此程序,将会有一个交互界面。 当选择修改时间选项时,用户将被要求输入新的时间值,如果输入无效,则显示错误消息。 当选择倒计时选项时,用户将被要求输入倒计时时长,程序将开始倒计时,并在倒计时结束时显示完整消息。

数字时钟,实时显示时间 (格式为时:分:秒),可以设置修改时间,并具有倒计时功能。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
#include <windows.h>

void gotoxy(int x, int y);  // 设置光标位置
void printTime(int h, int m, int s);  // 显示时间
void countDown(int seconds);  // 倒计时

int main()
{
    int h, m, s, option, timeToCount;

    while (1)
    {
        system("cls");  // 清屏
        time_t now = time(NULL);
        struct tm tm_now = *localtime(&now);
        h = tm_now.tm_hour;
        m = tm_now.tm_min;
        s = tm_now.tm_sec;
        printTime(h, m, s);  // 显示时间

        printf("\n\n[1] Set time\n");
        printf("[2] Count down\n");
        printf("[3] Exit\n");
        printf("Option: ");
        scanf("%d", &option);

        switch (option)
        {
            case 1:
                printf("\nEnter new time (hh:mm:ss): ");
                scanf("%d:%d:%d", &h, &m, &s);
                break;

            case 2:
                printf("\nEnter seconds: ");
                scanf("%d", &timeToCount);
                countDown(timeToCount);
                break;

            case 3:
                exit(0);

            default:
                printf("\nInvalid option. Try again.\n");
        }
    }

    return 0;
}

void gotoxy(int x, int y)
{
    COORD coord;
    coord.X = x;
    coord.Y = y;
    SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord);
}

void printTime(int h, int m, int s)
{
    printf("Current time: %02d:%02d:%02d", h, m, s);
}

void countDown(int seconds)
{
    system("cls");  // 清屏
    printf("Counting down: %d seconds\n\n", seconds);

    int remainingSeconds = seconds;

    while (remainingSeconds >= 0)
    {
        gotoxy(0, 2);
        printf("%02d:%02d:%02d", remainingSeconds / 3600, (remainingSeconds / 60) % 60, remainingSeconds % 60);
        remainingSeconds--;

        Sleep(1000);  // 等待1秒
    }

    system("cls");  // 清屏
    printf("Count down finished.\n\n");
}

这个样式的数字时钟需要使用easyX库编写,比较麻烦,改了一个倒计时6秒了代码,你参考一下。
运行效果:

img

代码原文连接(这个是正计时,类似秒表):
https://blog.csdn.net/qq_42330141/article/details/117689805

easyX库的安装参考:


6秒倒计时代码:

#include <graphics.h>
#include <conio.h>
#include <time.h>
#include <stdio.h>


//int g_mod = 0; //模式  0主界面  1显示时间  2倒计时模式

void name();                                // 绘制标题提示等
void one(int x, int y);
void two(int x, int y);
void three(int x, int y);
void four(int x, int y);
void five(int x, int y);
void six(int x, int y);
void seven(int x, int y);                    // one 到 seven 是组成电子数字的 7 个模块
void HpSleep(int ms);                        // 精确延时
void OUTNUMBER(int number, int x, int y);    // 将 7 个模块组成数字 09
void OUTPUT(int i, int j, int k);            // 在屏幕上显示

int main()
{
    initgraph(800, 600);
    setbkcolor(RGB(6, 31, 62));
    cleardevice();

    
    name();

    while (true)
    {
        OUTPUT(6, 0, 0); //初始6秒
        _getch();
        bool T = false;
        for (int i = 5; i >=0; i--)
        {
            if (T)
            {
                break;
            }
            for (int j = 9; j >=0; j--)
            {
                if (T)
                {
                    break;
                }
                for (int k = 9; k >=0; k--)
                {
                    if (_kbhit())
                    {
                        T = true;
                        break;
                    }
                    OUTPUT(i, j, k);
                    HpSleep(10);
                }
            }
        }
        _getch();
        _getch();
    }
    return 0;
}

void name()
{
    RECT r = { 240, 80, 560, 160 };

    settextcolor(RGB(163, 212, 255));
    settextstyle(60, 0, _T("楷体"));
    drawtext(_T("倒计时"), &r, DT_CENTER | DT_VCENTER | DT_SINGLELINE);
    

    settextcolor(RGB(254, 218, 168));
    settextstyle(20, 0, _T("楷体"));
    outtextxy(160, 450, _T("提示:按“空格键”开始,再按暂停,继续按将置零!"));
    settextcolor(RGB(252, 191, 116));
    //outtextxy(160, 480, _T("准确暂停到六秒整挑战成功!"));
}

void one(int x, int y)
{
    int pts[] = { 36 + x, 14 + y, 59 + x, 39 + y, 118 + x, 39 + y, 138 + x, 15 + y, 131 + x, 9 + y, 41 + x, 9 + y };
    setfillcolor(RGB(176, 215, 254));
    solidpolygon((POINT*)pts, 6);
}

void two(int x, int y)
{
    int pts[] = { 32 + x, 17 + y, 53 + x, 40 + y, 47 + x, 96 + y, 26 + x, 113 + y, 18 + x, 102 + y, 25 + x, 27 + y };
    setfillcolor(RGB(184, 249, 251));
    solidpolygon((POINT*)pts, 6);
}

void three(int x, int y)
{
    int pts[] = { 143 + x, 20 + y, 152 + x, 31 + y, 144 + x, 105 + y, 132 + x, 115 + y, 115 + x, 98 + y, 122 + x, 41 + y, };
    setfillcolor(RGB(187, 250, 255));
    solidpolygon((POINT*)pts, 6);
}

void four(int x, int y)
{
    int pts[] = { 46 + x, 101 + y, 113 + x, 101 + y, 127 + x, 116 + y, 111 + x, 131 + y, 45 + x, 131 + y, 29 + x, 117 + y };
    setfillcolor(RGB(187, 254, 219));
    solidpolygon((POINT*)pts, 6);
}

void five(int x, int y)
{
    int pts[] = { 25 + x, 120 + y, 43 + x, 136 + y, 38 + x, 199 + y, 15 + x, 223 + y, 6 + x, 209 + y, 15 + x, 127 + y };
    setfillcolor(RGB(245, 255, 192));
    solidpolygon((POINT*)pts, 6);
}

void six(int x, int y)
{
    int pts[] = { 132 + x, 119 + y, 144 + x, 128 + y, 136 + x, 213 + y, 129 + x, 222 + y, 107 + x, 201 + y, 115 + x, 134 + y };
    setfillcolor(RGB(245, 255, 190));
    solidpolygon((POINT*)pts, 6);
}

void seven(int x, int y)
{
    int pts[] = { 40 + x, 203 + y, 104 + x, 203 + y, 126 + x, 226 + y, 120 + x, 231 + y, 24 + x, 231 + y, 18 + x, 226 + y };
    setfillcolor(RGB(251, 221, 185));
    solidpolygon((POINT*)pts, 6);
}

void OUTNUMBER(int number, int x, int y)
{
    setfillcolor(RGB(6, 31, 62));
    solidrectangle(x, y, x + 160, y + 240);
    switch (number)
    {
    case 0:one(x, y); three(x, y); six(x, y); seven(x, y); five(x, y); two(x, y); break;
    case 1:three(x, y); six(x, y); break;
    case 2:one(x, y); three(x, y); four(x, y); five(x, y); seven(x, y); break;
    case 3:one(x, y); three(x, y); four(x, y); six(x, y); seven(x, y); break;
    case 4:two(x, y); three(x, y); four(x, y); six(x, y); break;
    case 5:one(x, y); two(x, y); four(x, y); six(x, y); seven(x, y); break;
    case 6:one(x, y); two(x, y); four(x, y); six(x, y); seven(x, y); five(x, y); break;
    case 7:one(x, y); three(x, y); six(x, y); break;
    case 8:one(x, y); three(x, y); six(x, y); seven(x, y); five(x, y); two(x, y); four(x, y); break;
    case 9:one(x, y); three(x, y); six(x, y); seven(x, y); two(x, y); four(x, y); break;
    }
}

void OUTPUT(int i, int j, int k)
{
    OUTNUMBER(i, 80, 180);
    setfillcolor(RGB(64, 157, 254));
    solidcircle(320, 240, 15);
    setfillcolor(RGB(163, 212, 255));
    solidcircle(320, 360, 15);
    OUTNUMBER(j, 400, 180);
    OUTNUMBER(k, 560, 180);
}

// 精确延时函数(可以精确到 1ms,精度 ±1ms)
// 记得加头文件 time.h
// by yangw80<yw80@qq.com>, 2011-5-4
void HpSleep(int ms)
{
    static clock_t oldclock = clock();        // 静态变量,记录上一次 tick
    oldclock += ms * CLOCKS_PER_SEC / 1000;    // 更新 tick
    if (clock() > oldclock)                    // 如果已经超时,无需延时
        oldclock = clock();
    else
        while (clock() < oldclock)                // 延时
            Sleep(1);                                // 释放 CPU 控制权,降低 CPU 占用率
}


用C语言编写数字时钟


#include<stdio.h>
#include<windows.h>
#include<stdlib.h>
 
int h = 0;
int m = 0;
int s = 0;
 
void Update();//数据更新
void Print();//打印时间
int main()
{
    int i;
    for (;;)
    {
        Update();
        system("cls");//清除控制台
        Print();
    }
    return 0;
}
 
void Update()
{
    s++;
    Sleep(1000);//延时1秒
    if (s == 60)
    {
        s = 0;
        m++;
    }
    if (m == 60)
    {
        m = 0;
        h++;
    }
    if (h == 24)
    {
        h = 0;
    }
 
}
 
void Print()
{
    printf("数字时钟:\n");
    printf("%d:%d:%d\n", h,m, s);
}
不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 你可以参考下这个问题的回答, 看看是否对你有帮助, 链接: https://ask.csdn.net/questions/7765027
  • 这篇博客也不错, 你可以看下【C语言习题】有一个已排好序的数组,要求输入一个数后,按原来排序的规律将它插入数组中。
  • 除此之外, 这篇博客: 使用C语言实现冒泡排序算法中的 冒泡排序属于交换排序的一种。所谓交换,就是根据序列中两个关键字的比较结果来确定这两个记录在序列中的位置。 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:

    冒泡排序的基本思想: 假设一个待排序列长度为n,从后往前(或从前往后)两两比较元素的值,若为正序则不操作,若为逆序(即A[i-1]>A[i])则交换它们,直到序列比较完,称为一趟“冒泡”,此时将最小的元素交换到待排序列的第一个位置,也是它的最终位置。下一趟排序时,上一趟确定的最小元素不再参与排序,每趟排序都将序列中最小的元素交换到第一个位置,依次类推,最多进行n-1趟冒泡就能把所有元素排好序。
    排序完成的判断条件: 使用flag作为标志位,每趟冒泡前初始为false,若发生元素交换则置为true,在一趟冒泡完成后判断flag值,若为true则继续排序,若为false则说明没有发生元素交换,排序完成。
    冒泡排序的性能分析:
    空间复杂度:仅进行元素交换需要常数个辅助空间,因此空间复杂度为O(1)
    时间复杂度:当待排序列已经有序时,明显进行一趟冒泡后flag值为false,排序完成,直接结束,比较次数为n-1,移动次数为0;当待排序列逆序时,需要进行n-1趟冒泡,第i趟排序需要进行n-i次比较,每次比较必须移动元素3次以交换位置,在这种情况下,
    在这里插入图片描述
    从而最坏情况下的时间复杂度为O(n2)。平均时间复杂度也为O(n2)
    举例说明冒泡过程:
    设一个初始序列为A={10,6,9,3,5,2}
    第一趟冒泡结果,A={2,10,6,9,3,5} (元素2到达最终位置)
    第二趟冒泡结果,A={2,3,10,6,9,5} (元素3到达最终位置)
    第三趟冒泡结果,A={2,3,5,10,6,9} (元素5到达最终位置)
    第四趟冒泡结果,A={2,3,5,6,10,9} (元素6到达最终位置)
    第五趟冒泡结果,A={2,3,5,6,9,10} (元素9到达最终位置)
    此时排序完成
    传统冒泡排序算法如下:

    #include <stdio.h>
    void bubblesort(int a[],int length);
    void swap(int a[],int i,int j);
    int main()
    {
       int array[6]={10,6,9,3,5,2}; /*定义一个数组*/
       int i;
       bubblesort(array,6);
       for(i=0;i<6;i++)
       {
           printf("array[%d]=%d\n",i,array[i]); /*输出排序后的数组*/
       }
    }
    void bubblesort(int a[],int n) /*冒泡排序算法*/
    {
        if(n==0||n<2) /*序列长度小于2直接返回*/
            return;
        int i,j,flag;
        for(i=0;i<n;i++) /*外层循环比较的次数*/
        {
            flag=0;
            for(j=n-1;j>i;j--) /*内层循环比较的范围*/
            {
                if(a[j-1]>a[j])
                {
                    swap(a,j-1,j);
                    flag=1;
                }
            }
            if(flag==0)
                return;
        }
    }
    void swap(int a[],int i,int j) /*交换元素位置*/
    {
        int temp;
        temp=a[i];
        a[i]=a[j];
        a[j]=temp;
    }
    

    运行结果如下图示:
    在这里插入图片描述

  • 您还可以看一下 李飞老师的C语言开发之数据结构与算法一课程中的 环形队列小节, 巩固相关知识点
  • 以下回答来自chatgpt:

    我可以给您提供一个简单的C语言时钟代码,实现实时更新显示数字。首先,需要用到库中的time()函数获取当前时间,并将其格式化输出。然后,用sleep()函数实现每秒更新一次。具体代码如下:

    #include <stdio.h>
    #include <time.h>
    #include <unistd.h>
    
    int main() {
        time_t currentTime;
        struct tm *info;
        char timeStr[10];
    
        while(1){
            //获取当前时间
            time(&currentTime);
            info = localtime(&currentTime);
    
            //格式化小时、分钟、秒钟的输出字符串
            strftime(timeStr, 10, "%H:%M:%S", info);
    
            //打印输出字符串
            printf("%s\r", timeStr);
            fflush(stdout);
    
            //等待1秒
            sleep(1);
        }
    
        return 0;
    }
    

    解释一下代码中的部分内容:

    • time(&currentTime)函数获取的是当前的时间戳,即距离1970年1月1日0时0分0秒的秒数;
    • localtime(&currentTime)函数将时间戳转换为本地时间,即本地时区的当前时间,并返回一个指向tm结构体的指针;
    • strftime(timeStr, 10, "%H:%M:%S", info)函数将符合tm结构体格式的时间格式化输出到timeStr字符数组中;
    • printf("%s\r", timeStr);使用了转义字符\r实现了实时的覆盖更新输出,避免不必要的屏幕刷屏;
    • fflush(stdout);函数强制刷新输出缓冲区,保证输出的实时性;
    • sleep(1)函数等待1秒,实现每秒更新一次。

    这样,我们就得到了一个简单的C语言数字时钟程序。


如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
 void display_time(int hour, int minute, int second) {
    printf("%02d:%02d:%02d\n", hour, minute, second);
}
 void modify_time(int* hour, int* minute, int* second) {
    printf("Enter the new time (HH:MM:SS): ");
    scanf("%d:%d:%d", hour, minute, second);
}
 void countdown(int seconds) {
    while (seconds > 0) {
        display_time(0, 0, seconds);
        sleep(1);
        seconds--;
    }
}
 int main() {
    int hour = 0, minute = 0, second = 0;
    int choice, countdown_seconds;
     while (1) {
        system("clear"); // 清屏
        display_time(hour, minute, second);
        printf("1. Modify time\n");
        printf("2. Countdown\n");
        printf("3. Exit\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
         switch (choice) {
            case 1:
                modify_time(&hour, &minute, &second);
                break;
            case 2:
                printf("Enter the number of seconds to countdown: ");
                scanf("%d", &countdown_seconds);
                countdown(countdown_seconds);
                break;
            case 3:
                exit(0);
            default:
                printf("Invalid choice!\n");
                break;
        }
         // 更新时间
        time_t now = time(NULL);
        struct tm* current_time = localtime(&now);
        hour = current_time->tm_hour;
        minute = current_time->tm_min;
        second = current_time->tm_sec;
    }
     return 0;
}

这个程序中, display_time 函数用于显示当前时间; modify_time 函数用于修改时间; countdown 函数用于倒计时。在 main 函数中,使用 switch 语句根据用户的选择调用不同的函数。程序每秒钟更新一次当前时间,并在屏幕上显示。

用C语言来写,最麻烦的是界面显示。如果要显示成题目要求的那种效果,就必须借助第三方的图形控件。如果只是要求字符界面,那就没有什么技术难度,起一个线程每秒更新时间进行打印就可以了。 如果还需要进行设置,就定义菜单或热键进行修改。

示例代码

#include <stdio.h>
#include <time.h>
#include <windows.h>

int main()
{
    while (1)
    {
        // 获取当前时间
        time_t now = time(NULL);
        struct tm* info = localtime(&now);
        
        // 输出时间
        printf("%02d:%02d:%02d\r", info->tm_hour, info->tm_min, info->tm_sec);
        fflush(stdout);
        
        // 每秒更新一次
        Sleep(1000);
    }
    
    return 0;
}