【问题标题】:Using single else statement for multiple if conditions [closed]对多个 if 条件使用单个 else 语句[关闭]
【发布时间】:2020-01-02 19:56:47
【问题描述】:

我正在为一个 arduino 项目编码,我遇到了这个问题,谁能帮帮我!

if(condition1){
//my codes here
}
if(condition2){
//my codes here
}
if(condition3){
//my codes here
}
......
if(condition100){
//my codes here
}
else{
my codes here
}

我想检查我所有的 if 条件,如果条件为真则执行代码,只有当 if 条件都不为真时才运行 else 语句。 请注意,我不能使用else if,因为我想检查所有 if 条件,如果没有一个为真,我想运行 else 如果条件不相互依赖

【问题讨论】:

  • 这个 Python、C++ 和 Java 有什么关系?
  • 您可以将本地布尔值最初设置为 false,然后在满足条件时更改为 true。 else 可以替换为 if 来检查此布尔值是否为真。
  • 您可以保留一个变量 int 并在每个 if 条件下递增它。然后在最后一个条件之后,检查您拥有的 if 块数。
  • 是的,决定你想要支持哪种语言...
  • Pattern Matching 在这里适用吗?虽然它仍然是 C++23 的提案。

标签: if-statement arduino


【解决方案1】:

您可以使用在您的任何ifs 中设置的布尔标志。

bool noPathTaken = true;
if ( condition1 ) {
    noPathTaken = false;
    // ...
}
if ( condition2 ) {
    noPathTaken = false;
    // ...
}
// ...
if ( noPathTaken ) { // this would be your "else"
    // ...
}

【讨论】:

    【解决方案2】:

    必须在每个测试中设置所有其他标志

    bool elseFlag = 1;
    
    if(condition1){
    elseFlag = 0;
    my codes here
    }
    
    if(condition2){
    elseFlag = 0;
    my codes here
    }
    
    if(condition3){
    elseFlag = 0;
    my codes here
    }
    ......
    if(condition100){
    elseFlag = 0;
    my codes here
    }
    
    if (elseFlag) {
     my codes here
    }
    

    因为else 只绑定到前面的测试操作中,这里是if(condition100) {

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-24
      • 2020-12-29
      • 2016-04-05
      • 2015-07-08
      相关资源
      最近更新 更多