gpt4 book ai didi

language-agnostic - 编写一段处理上升和下降的代码的最优雅的方法是什么?

转载 作者:行者123 更新时间:2023-12-04 06:48:08 25 4
gpt4 key购买 nike

我的微 Controller 项目中有以下代码:

if (newThrottle < currentThrottle)
{
for (int set = currentThrottle; set >= newThrottle; set--)
{
// Perform actions to set the throttle
}
}
else
{
for (int set = currentThrottle; set <= newThrottle; set++)
{
// Perform actions to set the throttle
}
}

如果不是很明显,此代码片段用于将电机 throttle 从当前值向上或向下倾斜到新值。

有没有更优雅的方式来写这个?

最佳答案

int add = (newThrottle > currentThrottle) ? 1 : -1;

while (newThrottle != currentThrottle)
{
// do your stuff
currentThrottle += add;
}

关于language-agnostic - 编写一段处理上升和下降的代码的最优雅的方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3499232/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com