我应该把 return 放在哪里?

Where do I place the return?

我正在编写一个函数来检查浮动传感器的输入。传感器给出数字 ON/OFF 信号。这是我写的,

int level_check(int sensorType, int FloatSensor)
{
  int level = 0;
  int buttonState = digitalRead(FloatSensor);
  if (sensorType == 1)
  {
    if (buttonState == LOW) 
      { 
          int level = 0;
          Serial.println( "WATER LEVEL - LOW"); 
    } 
      else 
      { 
          int level = 1;
          Serial.println( "WATER LEVEL - HIGH" ); 
      }
  }
  else
  {
    if (buttonState == LOW) 
      { 
          int level = 1;
          Serial.println( "WATER LEVEL - LOW"); 
    } 
      else 
      { 
          int level = 0;
          Serial.println( "WATER LEVEL - HIGH" ); 
      }
  }
  return level;
}

但是,无论传感器输出如何,无论我在哪里调用,级别总是 returned 为 0。 如果我进行此更改,代码将按预期工作。

if (buttonState == LOW) 
      { 
          int level = 0;
          Serial.println( "WATER LEVEL - LOW"); 
          return level;
    } 
      else 
      { 
          int level = 1;
          Serial.println( "WATER LEVEL - HIGH" ); 
          return level;
      }

上面的代码有什么问题?为什么最后不能用return

这是正确的代码。您在 if 内创建的 int level = //something; 仅位于 if 块的范围内,您在 else 内创建的 int level = //something; 仅位于 else 块的范围内。 int level = 0; 在您代码的第 2 行中位于函数 level_check.

的范围内
int level_check(int sensorType, int FloatSensor)
{
  int level = 0;
  int buttonState = digitalRead(FloatSensor);
  if (sensorType == 1)
  {
    if (buttonState == LOW) 
      { 
          level = 0;
          Serial.println( "WATER LEVEL - LOW"); 
    } 
      else 
      { 
          level = 1;
          Serial.println( "WATER LEVEL - HIGH" ); 
      }
  }
  else
  {
    if (buttonState == LOW) 
      { 
          level = 1;
          Serial.println( "WATER LEVEL - LOW"); 
    } 
      else 
      { 
          level = 0;
          Serial.println( "WATER LEVEL - HIGH" ); 
      }
  }
  return level;
}