Arduino 的基本数学计算问题

Basic math calculation issue with Arduino

我正在 Arduino 中进行基本操作,出于某种原因(这就是我需要你的原因)它给了我一个完全不合适的结果。下面是代码:

long init_H_top; //I am declaring it a long to make sure I got enough bytes
init_H_top=251*255/360; //gives me -4 and it should be 178

知道为什么会这样吗? 我很困惑...谢谢!

您的变量可能是long,但您的常量251255 , 和 360) 不是。

它们是 int 类型,因此将计算给出 int 结果,然后将其放入 long 变量,after any溢出已经造成了损害。

由于 Arduino 有一个 16 位 int 类型,251 * 255 (64005) 将超过 32767 的最大整数并导致像你这样的行为看到。值 64005 在 16 位二进制补码中是 -1531,当您将其除以 360 时,您得到大约 -4.25,截断为 -4

您应该使用 long 常量来避免这种情况:

init_H_top = 251L * 255L / 360L;