C++ Arduino-半字节到整数函数的不稳定结果
我有下面的代码,它给出了不稳定的结果C++ Arduino-半字节到整数函数的不稳定结果,c++,arduino,C++,Arduino,我有下面的代码,它给出了不稳定的结果 int nibbleToInt(String val) { int result; if(val.substring(3,4) == "1") { result += 1; } if(val.substring(2,3) == "1") { result += 2; } if(val.substring(1,2) == "1") { result += 4; } if(val.substring(0,1) == "1") { resul
int nibbleToInt(String val) {
int result;
if(val.substring(3,4) == "1") { result += 1; }
if(val.substring(2,3) == "1") { result += 2; }
if(val.substring(1,2) == "1") { result += 4; }
if(val.substring(0,1) == "1") { result += 8; }
return result;
}
我用nibbleToInt(“0010”)调用函数
并返回8663
编辑:
以下是因以下响应而产生的工作程序:
int nibbleToInt(String val) {
int result = 0;
if(val.substring(3,4) == "1") { result += 1; }
if(val.substring(2,3) == "1") { result += 2; }
if(val.substring(1,2) == "1") { result += 4; }
if(val.substring(0,1) == "1") { result += 8; }
return result;
}
如果初始化
result
,可能会看到不同的结果:否则(我相信)每次都会使用内存中的现有值。如果初始化result
,可能会看到不同的结果。)否则(我相信)每次都会使用内存中的现有值。您需要初始化结果
。您永远不会初始化结果。因此,该值将继续每次递增。您需要初始化result
。您永远不会初始化result。因此,该值将继续每次递增。