我有一个简单的arduino代码:
#define percentage 60
void setup() {
Serial.begin(9600);
int seconds = 682;
Serial.println(seconds);
Serial.println((seconds * percentage));//Should be 40920
Serial.println((seconds * percentage) / 100); //Should be 409
}
void loop() {}
当我运行它并打开串行显示器时,它显示了:
682
-24616
-246
,但应该显示以下:
682
40920
409
为什么我会遇到此计算错误?我该如何解决?预先感谢
您有一个整数溢出。Arduino上的int是16位,这意味着它的范围为-32,768至32,767。
https://www.arduino.cc/reference/en/language/variables/data-types/int/
这是一个溢出错误。尝试使用long long
或更大范围的其他内容。Arduino int
等于short
,因此我建议使用long
或long long
。正如Bennji正确说的那样,该范围从-32768到32767,适用于正常C 编译器的A short
。
也可以先分开然后乘。