2.2.9 实验9:结构体编程练习.doc

2.2.9 实验9:结构体编程练习.doc

2.2.9 实验结构体编程练习 在屏幕上模拟显示一个数字式时钟 按如下方法定义一个时钟结构体类型:struct clock { int hour; int minute; int second; }; typedef struct clock CLOCK; 然后,将下列用全局变量编写的时钟模拟显示程序改成用CLOCK结构体变量类型重新编写。已知用全局变量编写的时钟模拟显示程序如下:#include stdio.h #include stdio.h int hour, minute, second; /*全局变量定义*/ /*函数功能:时、分、秒时间的更新 函数参数:无 函数返回值:无 */ void Update(void) { second++; if (second == 60) /*若second值为60,表示已过分钟,则 minute值加1*/ { second = 0; minute++; } if (minute == 60)/*若minute值为60,表示已过小时,则 hour值加1*/ { minute = 0; hour++; } if (hour == 24)/*若hour值为24,则hour的值从0开始计时*/ { hour = 0; } }/*函数功能:时、分、秒时间的显示 函数参数:无 函数返回值:无 */ void Display(void)/*用回车符\r控制时、分、秒显示的位置*/ { printf(%2d:%2d:%2d\r, hour, minute, second); }/*函数功能:模拟延迟1秒的时间 函数参数:无 函数返回值:无 */ void Delay(void) { long t; for (t=0; t++) { /*循环体为空语句的循环,起延时作用*/ } } main() { long i; hour = minute = second = 0; /*hour,minute,second赋初值0*/ for (i=0; i100000; i++)/*利用循环结构,控制时钟运行的时间*/ { Update(); /*时钟更新*/ Display(); /*时间显示*/ Delay(); /*模拟延时1秒*/ } }void Update(struct clock *t) { static long m = 1; t-hour = m / 3600; t-minute = (m – 3600 * t-hour) / 60; t-second = m % 60; m++; if (t-hour == 24) { m = 1; } } void Update(struct clock *t) { static long m = 1; t-second = m % 60; t-minute = (m / 60) % 60; t-hour = (m / 3600) % 24; m++; if (t-hour == 24) { m = 1; } } ·138· C语言大学实用教程学习指导 ·137· 第2章 上机实验指导

文档评论(0)

1亿VIP精品文档

相关文档