首页 > 解决方案 > 是否可以仅在 C 中的一定时间后执行条件

问题描述

我想知道是否只有当条件在一定时间内为真时才能执行一段代码。

例如 :

if(position_goal_reached == 1) //but this should be true for 1 second)
    {do something;}

我不认为 C 能够做到这一点,但我想确定一下。

标签: ctimerconditional-statements

解决方案


我建议您使用time(),sleep()或.clock()usleep()

注 1:记得包含#include <unistd.h>或/和#include <time.h>

注意 2:如果您使用的是类 Unix 系统,那么 clock() 会出现一些问题。

我想你想做下一个:

#include <stdio.h>
#include <time.h>
int main(void)
{   
    clock_t start;
    start = clock();
    int milliseconds = 1000; // The amount of milliseconds that the conditional must take (This case 1 second)
    if(position_goal_reached == 1) 
    {   start_again_if:

        do something; //What you want to do must be here
 
         if ((int)(clock() - start) < milliseconds ) goto start_again_if;
    }
}

我希望这会有所帮助。


推荐阅读