gpt4 book ai didi

计数器的C程序

转载 作者:行者123 更新时间:2023-11-30 21:18:12 24 4
gpt4 key购买 nike

我想创建一个计数器。每隔 10 秒我想检查一次开关的状态。例如,如果开关闭合,则 10 秒计数器递增。如果打开,它将返回 sleep 状态,10 秒后再次唤醒并检查开关的状态。当计数达到例如 100 时,就做一些事情。我该怎么做

我的尝试是:

for(int i=0;i<100;i++){
if(SW=1) {
i++;
}
else
i=0;
}

最佳答案

我认为你需要更具体地回答这个问题。似乎您想在每次打开开关时重置计数器。您确定要这样吗?

无论如何,这可能就是你想要的

#include <stdio.h>
#include <time.h>
struct tm tm;
time_t start,enxd;
double sec;
int counter;
int main(){
int switchCounter = 0;
int checkSwitch;

checkSwitch = 1; // I put this in purpose since I have no idea how you're going to read the switch.
// Thus, this assumes the switch is always closed.

while(switchCounter != 100){
// 1. Wait for 10 seconds
sec = 0;
time(&start);

while(sec !=10){
++counter;
time(&enxd);
sec=difftime(enxd,start);
}

// 2. Read the state of the switch here.
// ..............

// 3. Simple if-else
if (checkSwitch == 1){ //switch is closed
switchCounter++;
printf("Counter incremented. Current = %i \n", switchCounter);
}
else //if switch is open
{
switchCounter = 0 ;// Iam confused here, is this what you want ?
printf("Switch is open \n");
}
}
// 4. Finally when your counter reaches 100, you wanna do something here
// ............................

return 0;
}

希望有帮助:)

关于计数器的C程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27171065/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com