首页 > 解决方案 > 对多个 if 条件使用单个 else 语句

问题描述

我正在为一个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 If 条件不相互依赖

标签: if-statementarduino

解决方案


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

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

推荐阅读