
C语言模拟时钟的代码,在vc++环境中运行。 50
展开全部
/**
给你一个用图形库实现的案例,如果你不会用图形库或者不用图形库也无所谓,看看思路也是
很好的。你说到钟表怎么转,那必然不是显示数字那么简单,所以这个小案例会对你有点帮助。
*/
#include <stdio.h>
#include <graphics.h>
#include <math.h>
#include <conio.h>
#define PI 3.141592653
void DrawDial();
void DrawHand(int hour, int min, int sec);
int main()
{
//创建一个窗口
initgraph(640, 480);
SYSTEMTIME t;
while (!kbhit())
{
DrawDial();
GetLocalTime(&t); //获取当地时间
DrawHand(t.wHour, t.wMinute, t.wSecond);
Sleep(1000); //大写的S!
BeginBatchDraw();
cleardevice();
EndBatchDraw();
}
getchar();
return 0;
}
//静态的表盘
void DrawDial()
{
circle(320, 240, 2);
circle(320, 240, 60);
circle(320, 240, 160);
circle(405, 210, 30);
outtextxy(290, 315, L"电子时钟");
//绘制刻度
int x, y;
for (int i = 0; i < 60; i++)
{
x = 320 + int(145 * sin(PI * 2 * i / 60)); //半径*sinA得出x轴偏移量
y = 240 + int(145 * cos(PI * 2 * i / 60));
/*
PI * 2 --> 360°
i * 60 --> 把360分成60分,占60份中的i份
*/
if (i % 15 == 0)
{
bar(x - 5, y - 5, x + 5, y + 5); //画矩形
}
else if (i % 5 == 0)
{
circle(x, y, 3);
}
else
putpixel(x, y, WHITE); //画一像素(点)
}
for (int i = 0; i <= 11; i++)
{
x = 405 + int(28 * sin(PI * 2 * i / 12));
y = 210 + int(28 * cos(PI * 2 * i / 12));
putpixel(x, y, WHITE);
}
}
//动态表针
void DrawHand(int hour, int min, int sec)
{
double ahour, amin, asec; //时分秒的弧度值
int xhour, yhour, xmin, ymin, xsec, ysec; //时分秒针的端点坐标
asec = sec * 2 * PI / 60;
amin = min * 2 * PI / 60 + asec / 60; //加上秒数带来的偏移
ahour = hour * 2 * PI / 12 + amin / 12;
/*
已走的格数 与 自己要走的格数的比例
+
下级已走的弧度 与 自己要走的格数的比例
*/
xsec = int(120 * sin(asec)); //120为秒针长度
ysec = int(120 * cos(asec));
xmin = int(100 * sin(amin));
ymin = int(100 * cos(amin));
xhour = int(70 * sin(ahour));
yhour = int(70 * cos(ahour));
//绘制表针
setlinestyle(PS_SOLID, 2);
setcolor(RED);
line(320 + xsec, 240 - ysec, 320 - xsec / 3, 240 + ysec / 3);
setlinestyle(PS_SOLID, 5);
setcolor(YELLOW);
line(320 + xmin, 240 - ymin, 320 - xmin / 3, 240 + ymin / 3);
setlinestyle(PS_SOLID, 7);
setcolor(LIGHTGREEN);
line(320 + xhour, 240 - yhour, 320 - xhour / 3, 240 + yhour / 3);
//自定义main函数时,手动将样式置回初始:
setlinestyle(PS_SOLID, 1);
setlinecolor(WHITE);
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询