c++ - 将更改限制为最大金额

标签 c++ c

假设我有:

int currentVelocity; //can be negative
int targetVelocity; //can also be negative

void updateVelocity() // called every 100ms
{
   int limit = 5;
}

如何在每次迭代时使速度更接近目标速度,且最大绝对变化为 5?

假设我的当前速度是 -20,目标速度是 -26

我的最大绝对增幅是 5。

首次调用 updateVelocity() 时,currentVelocity 变为 -25 再次调用时,currentVelocity为-26

除非目标速度改变,否则将永远如此。

必须在更新函数中添加什么才能做到这一点?

谢谢

最佳答案

一种简单的方法。

int currentVelocity; //can be negative
int targetVelocity; //can also be negative

void updateVelocity() // called every 100ms
{
   int limit = 5;
   int delta = targetVelocity - currentVelocity;

   if (delta > limit)
        currentVelocity += limit;
   else if (delta < -limit)
        currentVelocity -= limit;
   else
        currentVelocity = targetVelocity;
}

关于c++ - 将更改限制为最大金额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22276370/

相关文章:

c++ - 处理所有键盘输入( Hook )

c++ - GLEW 未在 MSYS2 上定位 OpenGL 函数

c++ - 字符串到 double 转换 C++

android - 跨平台项目中OpenGL绘图代码在哪里?规划我的引擎代码

c - 尝试使用通过 cmake 安装的 OpenCV-2.3.1 在 XCode 中运行示例 MacOSX FaceTracker 程序

c++ - 释放空指针

c - 在 void 指针的指针值处赋值

c - C 中的 int 和 char 数组

c++ - 有没有什么事情可以用 C 来完成,而不能用 C++ 来完成,反之亦然

带有指针的 c strcat