C编程: I want to make my stopwatch continuous but when a key is pressed it seems to only go in a one second increment and stop

标签 c

所以我的代码执行秒表功能。当我按下 DU 键时,我希望秒表增加计数或减少计数。它会这样做,但只持续一秒钟就停止了。我该如何让它连续。即我按下向下键,他们秒表就会倒计时。另外我将如何合并重置 key 。

#include <time.h>
#include <stdio.h>
#include <windows.h>
#include <conio.h>

int main()
{
    char c;
    int time_elapsed = 0;
    int flag = 0;

    for (;;) {
        if (flag == 0) {
            Sleep(1000);
            time_elapsed++;
            printf("Time elapsed since stopwatch started = %d seconds\n",
                   time_elapsed);
        }
        if (kbhit()) {
            c = getch();

            if (c == 's') {
                /* Stop */
                printf("You pressed s, so stopwatch is being stopped!\n");
                flag = 1;
            } else if (c == 'u' && flag == 1) {
                /* Up */
                time_elapsed = time_elapsed + 1;
                printf("You pressed u, so stopwatch reading is increased by 1 second!\n");
                printf("Time elapsed since stopwatch started = %d seconds\n",
                       time_elapsed);
            } else if (c == 'd' && flag == 1) {
                 /* Down */
                time_elapsed = time_elapsed - 1;
                printf("You pressed d, so stopwatch reading is decreased by 1 second!\n");
                printf("Time elapsed since stopwatch started = %d seconds\n",
                       time_elapsed);
            }
        }
    }

    return 0;
}

最佳答案

您需要一个变量来存储秒表的运行方向,在 sleep 之后,您需要根据该变量的值调整time_elapsed

关于C编程: I want to make my stopwatch continuous but when a key is pressed it seems to only go in a one second increment and stop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45425956/

相关文章:

c - 如何将 C 程序的字符串发送到 su 密码提示?

c - 我的指针和动态分配的实现是否正确?

c - 双向链接中的用户输入

c - 一个字节变量如何存储两个字节字符常量?

java - 哪种语言更适合计算机图形学

使用 PAPI_read_counters 计算 L1 缓存未命中会产生意外结果

sql - 如何从 C/C++ 应用程序进行 SQL 查询?

c - 浮点加法/乘法/除法

c - 地址分配中的问题

C 二维数组结构比较问题