c++ - Arduino 计算错误 - 在不应该的时候给出负值

标签 c++ math arduino

我有这个简单的 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/

关于c++ - Arduino 计算错误 - 在不应该的时候给出负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47466338/

相关文章:

c++ - 引用文献 : am I going to go out of scope?

javascript - 什么数学工具类似于 JavaScript 对象?

C 和 AVR pow 函数点亮 LED

c# - 分布式编程技术

c++ - 从 .cpp 文件调用 .mm 函数的链接器错误

c++ - C++中模板内部的返回类型可以控制吗?

math - 如何使用带有数学公式的对数似然相似度度量来计算相似度?

php - 按购物车中的项目拆分减少

arduino - 通过 Processing/Arduino 控制 Spotify

assembly - 设置 PINx 时会发生什么?为什么它有时会起作用?