【问题标题】:Increase a counter (++) only ONCE if an if statement is repeatedly true until false?如果 if 语句重复为真直到为假,则仅增加一次计数器 (++)?
【发布时间】:2018-03-11 15:39:02
【问题描述】:

抱歉标题太糟糕了,不知道如何正确解释。

我正在开发一个项目,该项目监控随环境变化的值。我的if 语句监视某个值何时超过一个数字并增加一个计数器以表明它已被触发。

我的问题是,当值超过目标值时,每次检查 if 语句并证明 true 时,它都会增加计数器。理想情况下,我希望它增加计数器一次,并且只在if 语句为true 时增加一次,直到证明false。然后一旦它再次被触发,它只会再次增加一次,不管它被证明是真的多少次。

让我解释一下:if 语句检查温度值,有时可能会长时间高于targetValue,导致每次检查时计数器都会增加(在我的情况下它会增加很多if 声明被证明是正确的)。这不是我想要的。

int targetValue = toInt(temperature);
if (targetValue > 30) 
{
    counterx ++;
}

【问题讨论】:

  • if 不是循环
  • 请张贴minimal reproducible example,显示您到目前为止所做的尝试。查看发布的代码,我们不知道代码 sn-p 与您的问题有何关联。
  • user3629249 已编辑,我希望现在可以更好地说明问题。

标签: c if-statement counter


【解决方案1】:

如果你想在状态改变时增加一些东西,那么你必须跟踪旧状态和新状态。当它们不相同时,将旧状态递增并将其设置为新状态,如下所示:

int state = get_state();
int old_state = state;

// starting control loop
while(1)
{
    state = get_state();
    if(old_state != state)
    {
        digitalWrite(led, HIGH);
        digitalWrite(relay, HIGH);
        counterx++;

        old_state = state;
    }

    // other stuff
    ...
}

【讨论】:

  • 稍微修改了一下,效果很好,决定使用布尔值。不过,非常感谢!
  • @rebble 使用 boolean 也可以,重要的是要记住最后的状态。
【解决方案2】:

你可以使用一个变量来测试:

if (difference > 30.0 && !triggered) 
{
    triggered = true;
    digitalWrite(led, HIGH);
    digitalWrite(relay, HIGH);
    counterx ++;
} else 
{
    triggered = false;
}

【讨论】:

    猜你喜欢
    • 2015-08-20
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多