访问必须在 if 语句中进行的 int

Accessing int that must be made inside if statement

本文关键字:int 语句 if 访问      更新时间:2023-10-16

所以我正在做一个使用颜色传感器的项目。我找到了一种定义 RGB 的方法,但我需要根据它的红绿还是蓝做一些事情......它的红绿或蓝的"决定"是在 if 语句内部做出的,那么我如何在它之外访问该颜色呢?(R = 1,B = 2,G = 3,因此更容易使用) 还是有另一种方法可以做到这一点?

总体任务是如果它为红色,则发出 1 声哔哔声, 绿色,2 哔声 ,与蓝色相同,不同的颜色组合会发出不同数量的哔哔声。

法典;

int s2 = 7;
int s3 = 8;
int s4 = 4;
int OUTpin= 4;
void setup(){
pinMode(7,OUTPUT);
pinMode(8,OUTPUT);
pinMode(4,INPUT);
Serial.begin(9600);
}
void loop(){
//Check Color reads pulse for RGB
// void checkred
digitalWrite(s2, LOW);
digitalWrite(s3, LOW);
unsigned int RW = 255 - (pulseIn(OUTpin, LOW)/ 400 - 1);  // turns into 0-255
delay(6000);
// void checkgreen
digitalWrite(s2,LOW);
digitalWrite(s3,HIGH);
unsigned int GW =  255 - (pulseIn(OUTpin, LOW)/  400 - 1);
delay(6000);
// void checkblue
digitalWrite(s2, HIGH);
digitalWrite( s3, HIGH);
unsigned int BW = 255 - (pulseIn(OUTpin, LOW) / 400 - 1);
delay(6000);
// seeing which color I got(r g or b)
if (RW > BW && RW > GW){
int color = 1;    // used to store that color, that's the 
// problem(because its inside if scope)
delay(7000);
}  else if  (GW > RW && GW > BW){
int color = 2;
delay(7000);
} else if  (BW > RW && BW > GW){
int color = 3;
delay(7000);
} 
}

在 if 语句之前声明color,并在块中分配给它:

// seeing which color I got(r g or b)
int color = 0;
if (RW > BW && RW > GW){
color = 1;    // no `int` here, just assigning
delay(7000);
}  else if  (GW > RW && GW > BW){
color = 2;
delay(7000);
} else if  (BW > RW && BW > GW){
color = 3;
delay(7000);
} 

如果您需要它在未来的循环调用中生存下来,请使其全局化。

一个非常干净的解决方案是将该功能移动到一个返回int的单独函数中。这也是使生成的int成为const变量的唯一方法,这是一种很好的做法。

例:

int ChooseColor(unsigned int RW, unsigned int BW, unsigned int GW)
{
// seeing which color I got(r g or b)
if (RW > BW && RW > GW) {
return 1;
} else if  (GW > RW && GW > BW) {
return 2;
} else if  (BW > RW && BW > GW) {
return 3;
}
assert(false);
return 0; // to prevent compiler warnings
}

然后在loop中,执行以下操作:

int const color = ChooseColor(RW, BW, GW);
delay(7000);

为什么不在 if-else if 阶梯之外声明它并在条件中设置其值? 像这样,

int i;
if(...)
{
i=1;
}
else if(...)
{ 
i=2;
}

。等等

int放在 if 语句之外。无法访问它们的原因是因为它们是if语句的局部变量。因此,一旦if结束,其中声明的所有变量,包括您的int都将被销毁。

您有时可能会利用这一点来发挥自己的优势,例如用于内存管理,但对于今天,简短的答案是简单地将int放在外面并在if中赋予它一个值。

相关文章: