Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Math Arduino的基本数学计算问题_Math_Arduino_Arduino Uno - Fatal编程技术网

Math Arduino的基本数学计算问题

Math Arduino的基本数学计算问题,math,arduino,arduino-uno,Math,Arduino,Arduino Uno,我在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 知道为什么会这样吗? 我很困惑。。。谢谢 变量可能是长的,但常量(251、255和360)不是 它们是int类型

我在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
知道为什么会这样吗? 我很困惑。。。谢谢

变量可能是
长的
,但常量(
251
255
360
)不是

它们是
int
类型,因此将计算得出
int
结果,然后在溢出造成损坏后,将其放入
long
变量中

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

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

init_H_top = 251L * 255L / 360L;
变量可能是
长的
,但常量(
251
255
360
)不是

它们是
int
类型,因此将计算得出
int
结果,然后在溢出造成损坏后,将其放入
long
变量中

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

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

init_H_top = 251L * 255L / 360L;

回答得好!我一直在期待类似的事情——这让我很不安!:)回答得好!我一直在期待类似的事情——这让我很不安!:)