访问必须在 if 语句中进行的 int
Accessing int that must be made inside if statement
所以我正在做一个使用颜色传感器的项目。我找到了一种定义 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
中赋予它一个值。
相关文章:
- 比较if语句中的数组值和int值
- "类模板示例<int>;"语句对 C++11 是什么意思?
- "1L << count"是什么意思?如何使用超出"unsigned long long int? "范围的语句编号打印?
- 在 IF 语句中比较 int 时出现奇怪的行为
- switch 语句和对象隐式 int 转换
- 访问必须在 if 语句中进行的 int
- 为什么所有可能的整数都"true"在 C++ 的 if 语句内的 long int 范围内,而 0 不是?
- 这个语句到底是什么意思 stack<int, list<int> > 它与 stack 有何不同<int>?
- c中的neo4j-client,在语句中编码的原始类型(即int)
- 使用 map<string,int> 在开关大小写语句中使用字符串
- switch 语句中从 int 到枚举类的隐式转换
- 为什么“vector<int>(v1);”语句失败
- 为什么这个语句"priority_queue <pair<int,int>,vector<pair<int,int> >compare>pq;"在C++
- 返回 std::string 的函数在没有 return 语句的情况下崩溃,这与返回 int 而不返回语句的函数不同
- 来自另一个类的 switch 语句中的静态 const int 会导致错误 C2051:案例表达式不是常量
- 确定 int 是否不为 0,没有 if 语句
- 我将如何在不使用 if 语句、字符数组、apstring 或 atoi 的情况下将带有两位数字的字符串转换为 int
- 使用for语句计算int输入的和
- 视觉 为什么即使我没有包含 return 语句,C++中返回"int"的函数也会编译?
- 如果一个指定返回类型为int的函数没有任何返回语句,即不返回值,它会返回垃圾值吗