Arduino Uno在计算时出错



所以我一直在用我的Arduino制作一个计算器,我就是这么做的。尽管如此,它并没有像我预期的那样工作。当我输入简单的计算时,它会很好地吐出来,但当我输入复杂的计算时它会发疯!它告诉我9999*9大约是-14554或类似的东西。这是代码:

#include <LiquidCrystal_I2C.h>
#include <LCD.h>
#include <Keypad.h>
LiquidCrystal_I2C lcd(0x27, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
const byte ROWS = 4;
const byte COLS = 4;
char keys [ROWS] [COLS] = {
{'1', '2', '3', '+'},
{'4', '5', '6', '-'},
{'7', '8', '9', '*'},
{'C', '0', '=', '/'}
};
byte rowPins[ROWS] = {13,12,11,10};
byte colPins[COLS] = {9,8,7,6};
Keypad myKeypad = Keypad(makeKeymap(keys), rowPins, colPins, ROWS, COLS);
boolean ansPresent = false;
boolean opSelected = false;
boolean final = false;
String num1, num2;
int answer;
char op;
void setup() {
lcd.begin(16,2);
lcd.setCursor(0,0);
lcd.print("Arduino");
lcd.setCursor(0,1);
lcd.print("Calculator");
delay(2000);
lcd.clear();
lcd.setCursor(0,0);
}
void loop(){
char key = myKeypad.getKey();
if (ansPresent == false && key != NO_KEY && (key=='1'||key=='2'||key=='3'||key=='4'||key=='5'||key=='6'||key=='7'||key=='8'||key=='9'||key=='0')) {
if (opSelected == false) {
num1 = num1 + key;
lcd.setCursor(0, 0);;
lcd.print(num1);
}
else {
num2 = num2 + key;
lcd.setCursor(0, 1);
lcd.print(num2);
final = true;
}
}
else if (ansPresent == false && opSelected == false && key != NO_KEY && (key == '/' || key == '*' || key == '-' || key == '+')) {
opSelected = true;
op = key;
lcd.setCursor(15, 0);
lcd.print(op);
lcd.setCursor(15, 1);
lcd.print("=");
}
else if (ansPresent == false && final == true && key != NO_KEY && key == '=') {
if (op == '+'){
answer = num1.toInt() + num2.toInt();
}
else if (op == '-') {
answer = num1.toInt() - num2.toInt();
}
else if (op == '*') {
answer = num1.toInt() * num2.toInt();
}
else if (op == '/') {
answer = num1.toInt() / num2.toInt();
}     
lcd.clear();
lcd.setCursor(0,0);
lcd.print(answer);
ansPresent = true;
}
else if (key != NO_KEY && key == 'C') {
lcd.clear();
ansPresent = false;
opSelected = false;
final = false;
num1 = "";
num2 = "";
answer = 0;
op = ' ';
}
}

它这么做有原因吗?

这看起来确实像是一个16位有符号整数的溢出,而这正是Arduino Uno内部使用的。数字>32767不能用这个来表示。这不是错误,这是硬件的限制,它只是16位。

需要使用多个int值才能容纳更大的值。

Arduino Uno使用ATmega。在该板上,int是一个范围为-32768到32767的16位有符号值。

这意味着你的乘法溢出,你看到的打印出来的是——根据文档——";不可预测";。所以一定不要那样做。

https://www.arduino.cc/reference/en/language/variables/data-types/int/

注释和警告当签名变量超过其值时它们溢出的最大或最小容量。溢出的结果是不可预测的,因此应该避免这种情况。典型的溢出是变量";滚动";从其最大容量到它的最小值,反之亦然,但情况并非总是如此。如果你想要这种行为,请使用无符号整数

最新更新