在 c++ 中布尔值上不是运算符
NOT operator on Boolean in c++
我正在尝试在我的程序中使用此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因此,当 timer0 超过间隔时,if 语句应计算 是假的
超过间隔时,"(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 >= 5
或timer >= interval
表示
博士您的代码工作正常。
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- 变量定义到C++布尔值转换
- 如何确保在使用基于布尔值的两个方法之一调用方法时避免分支预测错误
- 隐式常量/非常量运算符布尔
- 重载更少,则运算符返回相反的布尔值
- 将此布尔值传递给此函数的最有效方法是什么?
- 如何设置 c++ 类的布尔值?
- 使用 MAKEWORD / MAKEWPARAM 使用布尔值而不是布尔值
- 将流运算符>>评估为布尔值
- 为什么在布尔值上使用两个"!"运算符?
- 重载运算符<<输出布尔值.为什么
- 对布尔值使用逐位not运算符(~)是否会调用Undefined Behavior
- 在 c++ 中布尔值上不是运算符
- 在C++中,一元减号运算符如何处理布尔值
- 移动后是否应该 std::function::运算符布尔值返回 false
- Int 被视为布尔值和运算符
- 运算符 |= 表示 C++ 中的布尔值
- 错误:无法将运算符从分数转换为布尔值
- 如何创建一个合适的布尔值 员工::运算符==(const Employee & rhs) const
- 不能使用运算符 != 表示布尔值