在 c++ 中布尔值上不是运算符

NOT operator on Boolean in c++

本文关键字:运算符 布尔值 c++      更新时间:2023-10-16

我正在尝试在我的程序中使用此Arduino代码,LED将保持亮起持续 5 秒,然后自行关闭

#include <elapsedMillis.h>
int led = 13 ;
elapsedMillis timer0 ;
#define interval 5000
boolean timer0Fired ;
// the setup routine runs once when you press reset:
void setup() 
{
    pinMode(led, OUTPUT);
    digitalWrite(led, HIGH);
    timer0Fired = false;
    timer0 = 0; // clear the timer at the end of startup
}
void loop()
{
    if ((!timer0Fired) && (timer0 > interval))
    {
        timer0Fired = true;      // don't execute this again
        digitalWrite(led, LOW);  // turn led off after 5 sec
    }
}

我不明白 if 语句在循环中是如何工作的,!timer0Fired 的计算结果应该为 1,但当我打印出来时它是 0,所以当 timer0 超过间隔 if 语句的计算结果应为 false,我在 UNO 上尝试过它并且它可以工作。

!timer0Fired 的计算结果应该为 1,但当我打印出来时它是 0

当你打印它时,你打印的是"!timer0Fired"还是"timer0Fired"?它将解释输出。

因此,当 timer0 超过间隔时,if 语句应计算 是假的

目前,当 timer0

超过间隔时,"(timer0>间隔)"的计算结果为 true,而不是相反。难道不是吗?

这只是一个基本的编程逻辑。

想象一下,你想数到 5 并调用某个函数,例如 DoSomething,在和无休止的循环。

int count = 0;
bool called = false; // DoSomething not called yet
while (true) // main loop
{
    ++count;
    if (count == 5)
    {
        // the count is 5
        if (called == false)
        {
            // function not called yet, call it!
            called = true;
            DoSomething();
        }
    }
}

这在某种程度上似乎是无稽之谈。等着吧...

但是,您面临的问题是您没有像我这样的简单计数器count。相反,您正在使用的计时器可能相差几毫秒,并且即使代码延迟,您仍然希望代码执行。

例如:

int count = 0;
bool called = false; // DoSomething not called yet
while (true) // main loop
{
    count += 2; // emulate counter being late
    if (count >= 5) // note that count == 5 will be always false here...
    {
        // the count is 5 or more
        if (called == false)
        {
            // function not called yet, call it!
            called = true;
            DoSomething();
        }
    }
}

现在这完全反转了if s 的值。这样,应用程序几乎总是通过第一个if,但只通过一次第二个。为了优化这一点,您可以交换if

if (called == false)
{
    if (count >= 5)
    {
        called = true;
        DoSomething();
    }
}

现在,您可能知道,可以使用运算符轻松地将这些嵌套if语句分组&&一个。此外,通过使用 !called 可以减少called == false的详细程度。这最终导致

while (true) // main loop
{
    count += 2; // emulate counter being late
    if (!called && count >= 5)
    {
        // function not called yet and count is already 5 or more
        called = true;
        DoSomething();
    }
}

所以这是怎么回事:
a) 你只想执行一段
代码一次 - 由代码中的bool called = false; if (!called) called = true;逻辑或timer0fired表示

b)你想延迟通话,直到某个计时器达到一定数量
- 在您的示例中由count >= 5timer >= interval表示


博士您的代码工作正常。