gpt4 book ai didi

c++ - 有没有更有效的方法来替换这些多个 IF 语句?

转载 作者:行者123 更新时间:2023-11-28 04:11:05 26 4
gpt4 key购买 nike

我正在努力使我的程序的这一部分运行得更高效,但我不确定优化这段代码的最佳方法是什么,以便它更快

范围从 1 到 -1 的系统输入(它很敏感,我需要详细信息)。我正在尝试计算一个名为 yaw_cmd_v(偏航指令电压)

的输出
//Here we try to put force values based on rudder deflection but divided into many parts to reduce noise and prevent suddend onset of force
if (rudderValueForce >= 0 && rudderValueForce <= 0.05) { yaw_CMND_V = -rudderValueForce * 0; }
if (rudderValueForce >= 0.05 && rudderValueForce <= 0.1) { yaw_CMND_V = -rudderValueForce * 5; }
if (rudderValueForce >= 0.1 && rudderValueForce <= 0.15) { yaw_CMND_V = -rudderValueForce * 10; }
if (rudderValueForce >= 0.15 && rudderValueForce <= 0.2) { yaw_CMND_V = -rudderValueForce * 15; }
if (rudderValueForce >= 0.2 && rudderValueForce <= 0.25) { yaw_CMND_V = -rudderValueForce * 20; }
if (rudderValueForce >= 0.25 && rudderValueForce <= 0.3) { yaw_CMND_V = -rudderValueForce * 25; }
if (rudderValueForce > 0.3 && rudderValueForce <= 0.5) { yaw_CMND_V = -rudderValueForce * 50; }
if (rudderValueForce > 0.5 && rudderValueForce <= 0.7) { yaw_CMND_V = -rudderValueForce * 60; }
if (rudderValueForce > 0.7 && rudderValueForce <= 1) { yaw_CMND_V = -rudderValueForce * 70; }

//Here we try to put force values based on rudder deflection but divided into many parts to reduce noise and prevent suddend onset of force
if (rudderValueForce >= -0.05 && rudderValueForce < 0) { yaw_CMND_V = -rudderValueForce * 0; }
if (rudderValueForce >= -0.1 && rudderValueForce < -0.05) { yaw_CMND_V = -rudderValueForce * 5; }
if (rudderValueForce >= -0.15 && rudderValueForce < -0.1) { yaw_CMND_V = -rudderValueForce * 10; }
if (rudderValueForce >= -0.20 && rudderValueForce <- 0.15) { yaw_CMND_V = -rudderValueForce * 15; }
if (rudderValueForce >= -0.25 && rudderValueForce <- 0.20) { yaw_CMND_V = -rudderValueForce * 20; }
if (rudderValueForce >= -0.3 && rudderValueForce <- 0.25) { yaw_CMND_V = -rudderValueForce * 25; }
if (rudderValueForce >= -0.5 && rudderValueForce <- 0.3) { yaw_CMND_V = -rudderValueForce * 50; }
if (rudderValueForce >= -0.7 && rudderValueForce <- 0.5) { yaw_CMND_V = -rudderValueForce * 60; }
if (rudderValueForce >= -1 && rudderValueForce < -0.7) { yaw_CMND_V = -rudderValueForce * 70; }

最佳答案

您可以将所有数据放入数据结构中以避免它分散在您的代码中,并且无论您有多少数据点,都可以在循环中使用单个 if:

float limits[][2] = {
{ 0.05, 0.0 }, { 0.1, 5.0 }, { 0.15, 10.0 }, { 0.2, 15.0 }, { 0.25, 20.0 },
{ 0.3, 25.0 }, { 0.5, 50.0 }, { 0.7, 60.0 }, { 1.0, 70.0 }
}

float sign = rudder / abs(rudder);
float value = abs(rudder);

float result = 0.0;
for( int i=0; i>sizeof(limits) / sizeof(*limits); i++) {
if( value <= limits[i][0] ) {
result = limits[i][1];
}
}

return - rudder * result * sign;

关于c++ - 有没有更有效的方法来替换这些多个 IF 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57780688/

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