请用c语言编一段控制流水灯的代码
以下是一个用C语言编写的控制流水灯的代码示例:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <windows.h>
// 定义流水灯的灯珠数量和延迟时间
#define NUM_LED 8
#define DELAY_TIME 500
// 控制流水灯的函数
void controlFlowingLights() {
int lights[NUM_LED] = {0}; // 流水灯的灯珠状态,0表示关闭,1表示打开
int currentIndex = 0; // 当前亮起的灯珠索引
while (1) {
// 关闭上一个亮起的灯珠
lights[currentIndex] = 0;
// 计算下一个亮起的灯珠索引
currentIndex = (currentIndex + 1) % NUM_LED;
// 打开下一个亮起的灯珠
lights[currentIndex] = 1;
// 输出流水灯的状态
for (int i = 0; i < NUM_LED; i++) {
printf("%d", lights[i]);
}
printf("\r");
fflush(stdout);
// 延迟一段时间
Sleep(DELAY_TIME);
}
}
int main() {
controlFlowingLights();
return 0;
}
这个代码使用了一个数组来表示流水灯的灯珠状态,通过不断更新灯珠的状态和延迟一段时间来实现流水灯的效果。在 Windows 环境下,可以使用 <conio.h> 头文件中的 _getch() 函数来实现按下任意键停止流水灯
原文地址: https://www.cveoy.top/t/topic/hQgY 著作权归作者所有。请勿转载和采集!