在stackoverflow上查到了类似的问题,原因是数值溢出造成的

————————————————————————————
《Arduino Arithmetic error negative result》
问题:
I am trying to times 52 by 1000 and i am getting a negative result
int getNewSum = 52 * 1000;
but the following code is ouputting a negative result: -13536
————————————————————————————
解决方法1:将int更换成更大的data type
int:
16 bit: from -32,768 to 32,767
32 bit: from -2,147,483,648 to 2,147,483,647
unsigned int: from 0 to 65,535
long: from 2,147,483,648 to 2,147,483,647
unsigned long: from 0 to 4,294,967,295
解决方法2:化简计算方法
比如我要实现一个倒计时的程序,以前的计算方法是这样的:
int countDownData[2]={25};//minute,second
val = (countDownData[0]*60000 + countDownData[1]*1000)/intervalSpeed
换成下面这样后,结果虽然一样,但通过分开计算,先算除法,计算过程中产生的数值就会小很多
val = countDownData[0]*(60000/intervalSpeed) + countDownData[1]*(1000/intervalSpeed);
参考文档:
------------------------------
《数值溢出(arithmetic overflow)问题与解决方案》
https://blog.csdn.net/lanchunhui/article/details/52425939--------------------------------
《Arduino Arithmetic error negative result》
https://stackoverflow.com/questions/20594628/arduino-arithmetic-error-negative-result