c语言编程电子时钟
时间: 2023-09-18 10:13:55 浏览: 53
好的,下面是一个简单的C语言编程电子时钟的代码,你可以参考一下:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <Windows.h>
void gotoxy(int x, int y) // 光标移动函数
{
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void setcolor(int color) // 设置字体颜色函数
{
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), color);
}
void drawClock() // 绘制模拟时钟函数
{
int i, j;
int x = 40, y = 10;
int r = 8;
gotoxy(x, y);
printf("╔═════════════╗");
for (i = 1; i <= 12; i++) {
gotoxy(x, y + r);
printf("║ ║");
gotoxy(x, y);
printf("║%2d", i);
gotoxy(x + 15, y);
printf("║%2d", i + 12);
x += r * 2;
if (i == 6) {
x = 40;
y += r * 2;
}
}
gotoxy(40, y);
printf("╚═════════════╝");
}
void eraseHour(int hour, int r) // 时针擦除函数
{
int x, y;
x = 40 + (r - 2) * sin(hour * 30 * 3.14 / 180);
y = 10 - (r - 2) * cos(hour * 30 * 3.14 / 180);
gotoxy(x, y);
printf(" ");
}
void drawHour(int hour, int r) // 时针绘制函数
{
int x, y;
x = 40 + (r - 2) * sin(hour * 30 * 3.14 / 180);
y = 10 - (r - 2) * cos(hour * 30 * 3.14 / 180);
gotoxy(x, y);
setcolor(4); // 红色
printf("▲");
setcolor(7); // 白色
}
void eraseMinute(int minute, int r) // 分针擦除函数
{
int x, y;
x = 40 + (r - 1) * sin(minute * 6 * 3.14 / 180);
y = 10 - (r - 1) * cos(minute * 6 * 3.14 / 180);
gotoxy(x, y);
printf(" ");
}
void drawMinute(int minute, int r) // 分针绘制函数
{
int x, y;
x = 40 + (r - 1) * sin(minute * 6 * 3.14 / 180);
y = 10 - (r - 1) * cos(minute * 6 * 3.14 / 180);
gotoxy(x, y);
setcolor(2); // 绿色
printf("▲");
setcolor(7); // 白色
}
void eraseSecond(int second, int r) // 秒针擦除函数
{
int x, y;
x = 40 + r * sin(second * 6 * 3.14 / 180);
y = 10 - r * cos(second * 6 * 3.14 / 180);
gotoxy(x, y);
printf(" ");
}
void drawSecond(int second, int r) // 秒针绘制函数
{
int x, y;
x = 40 + r * sin(second * 6 * 3.14 / 180);
y = 10 - r * cos(second * 6 * 3.14 / 180);
gotoxy(x, y);
setcolor(9); // 蓝色
printf("▲");
setcolor(7); // 白色
}
void drawDigitalClock(int hour, int minute, int second) // 绘制数字时钟函数
{
gotoxy(40, 20);
printf("%02d:%02d:%02d", hour, minute, second);
}
int main()
{
int hour, minute, second;
time_t t;
system("title 电子时钟"); // 设置窗口标题
system("mode con cols=80 lines=30"); // 设置窗口大小
drawClock(); // 绘制模拟时钟
while (1) {
t = time(NULL);
hour = localtime(&t)->tm_hour % 12; // 获取小时
minute = localtime(&t)->tm_min; // 获取分钟
second = localtime(&t)->tm_sec; // 获取秒钟
eraseHour(hour, 6); // 擦除时针
drawHour(hour, 6); // 绘制时针
eraseMinute(minute, 7); // 擦除分针
drawMinute(minute, 7); // 绘制分针
eraseSecond(second, 8); // 擦除秒针
drawSecond(second, 8); // 绘制秒针
drawDigitalClock(localtime(&t)->tm_hour, minute, second); // 绘制数字时钟
Sleep(20); // 延时20毫秒
}
return 0;
}
```
这个电子时钟程序使用了Windows.h头文件中的一些函数来实现光标移动和字体颜色设置等操作。同时,使用time.h头文件中的time()函数获取当前系统时间,并绘制模拟时钟和数字时钟。