【发布时间】:2020-11-05 04:12:17
【问题描述】:
这是我的代码,当我运行程序时,节流阀为 -18,当我进行数学运算时,我得到 77.941... 这就是我要找的。我知道这是一个 EDQ“非常愚蠢的问题”,我很可能随时都会遇到 FIF,“额头上的拳头”时刻,但我现在被困住了。仅供参考,在 Atmega 328P 上使用 Windows 10 上的 Arduino IDE 对其进行编程。
以下示例打印 -18,根据我的计算,它应该是 77.941...
int throttle = (((800 - 270) * 100) / 680);
Serial.println(throttle);
这是可视化代码...
throttle = (((throttleSensor - oldMinValue) * (newMax - newMin)) / (oldMax - oldMin));
我正在尝试这样做,Convert a number range to another range, maintaining ratio
另外,我应该补充一点,当结果低于 47 时它工作正常,高于它会翻转为负数。
【问题讨论】:
-
请尝试生成minimal, reproducible example。在不知道
throttleSensor、oldMinValue、newMax、newMin、oldMax和oldMin是如何设置的情况下,我们最多只能猜测可能出了什么问题。 -
这些实际数字就是我们在这个问题中要处理的。为了清楚起见,我现在进行了编辑
-
这可能是因为
ints 在您的系统中是 16 位的,并且您在 (800 - 270) * 100 = 53,000 上有溢出。带符号的 16 位整数最多只能达到 32,767。 -
Arduino 是 8 位 MCU,因此 int 仅包含 16 位。您需要改用
long:int throttle = ((800 - 270) * 100L) / 680 -
谢谢,我只是自己想到了这个问题,正在努力修复它,我会让你知道我想出了什么。
标签: c++ math arduino linear-programming