gpt4 book ai didi

c++ - 为什么这两个值在 arduino 上不相等?

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:46:49 26 4
gpt4 key购买 nike

我正在制作一个小型 arduino 二进制计算器。

我让代码运行一些小数学题:✓

我将答案从十进制转换为二进制:✓

我用 for 循环遍历二进制答案,然后打开面包板上的 LED 以显示答案:✗

//First led in pin 2
void setup()
{
Serial.begin(9600);
}
//I have the code run some little math problem:Check
int a=2;
int b=5;
int answer=b-a;


int myNum = answer;
void loop(){
//I convert the answer from decimal to binary:Check
int zeros = 8 - String(myNum,BIN).length();
String myStr;
for (int i=0; i<zeros; i++) {
myStr = myStr + "0";
}
myStr = myStr + String(myNum,BIN);
Serial.println(myStr);

//I loop through the binary answer with a for loop
//and power on LEDs on a bread board to display the answer:Not check

for(int i=2;i<=9;i=i+1){

//This part doesn't work

if(int(myStr[i-2])==1){
digitalWrite(int(i), HIGH);
}else{Serial.println(myStr[i-2]);}
}
while(true){}
}

出于某种原因,它说 int(myStr[i-2]) 永远不等于 1。

在此先感谢您的帮助。

最佳答案

int() 转换很可能没有按照您的预期进行。它不会将值从数字字符串转换为二进制值。相反,您可能想检查字符串中的值是否为 ascii 数字。

if(myStr[i - 2] == '1')
// ^^^ single quotes to specify character value.
{
digitalWrite(int(i), HIGH);
}
else
{
Serial.println(myStr[i - 2]);
}

关于c++ - 为什么这两个值在 arduino 上不相等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21030349/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com