如何结束#include <stdio.h> #include <graphics.h> #include<time.h> clock_t Start_time; clock_t End_time; int time_1; char str[100]; int main() { initgraph(200, 200, SHOWCONSOLE);//init 初始化 graph 图像窗口 SHOWCONSOLE 显示控制台 setbkcolor(RGB(225, 115, 100));//设置背景颜色 BeginBatchDraw(); //双缓冲绘图,防止屏闪 Start_time = clock(); while (1) { cleardevice(); End_time = clock(); time_1 = (int)((End_time - Start_time) / CLOCKS_PER_SEC); settextstyle(20, 0, "宋体"); setcolor(BLACK);// sprintf_s(str, " %d s", time_1); outtextxy(10, 10, str); EndBatchDraw();//双缓冲绘图 } return 0; }
时间: 2024-03-05 18:48:58 浏览: 15
这段代码本身没有错误,可以正常运行。但是由于 while 循环中没有任何退出条件,所以程序会一直运行,无法结束。因此你需要添加一个退出循环的条件,以便程序可以正常结束。
下面是一个修改后的代码,添加了一个 ESC 键退出循环的条件:
```c++
#include <stdio.h>
#include <graphics.h>
#include <conio.h>
#include <time.h>
clock_t Start_time;
clock_t End_time;
int time_1;
char str[100];
int main() {
initgraph(200, 200, SHOWCONSOLE); // init 初始化 graph 图像窗口 SHOWCONSOLE 显示控制台
setbkcolor(RGB(225, 115, 100)); // 设置背景颜色
BeginBatchDraw(); // 双缓冲绘图,防止屏闪
Start_time = clock();
while (1) {
cleardevice();
End_time = clock();
time_1 = (int)((End_time - Start_time) / CLOCKS_PER_SEC);
settextstyle(20, 0, "宋体");
setcolor(BLACK);
sprintf_s(str, " %d s", time_1);
outtextxy(10, 10, str);
EndBatchDraw(); // 双缓冲绘图
if (_kbhit() && _getch() == 27) { // 如果按下 ESC 键,则退出循环
break;
}
}
getch();
closegraph();
return 0;
}
```
在这个修改后的代码中,使用 _kbhit 函数检测是否有键盘输入,如果有,则使用 _getch 函数获取键盘输入的字符。如果获取到的字符是 ESC 键,则退出循环,程序正常结束。