如何将 if 语句更改为开关

how to change an if statement to a switch

本文关键字:开关 语句 if      更新时间:2023-10-16

如何将以下代码从 if 语句更改为开关。 是否可以按照下面显示的顺序(0,0,0,1,1,1,2,2,2,2,2)递增速度[0]变量节点属于类型对象。

if (node->speed[0] > system->velocity)
    node->speed[0] = pSystem->velocity;
else if (node->speed[0] < pSystem->nVelocity)
    node->speed[0] = pSystem->nVelocity;
if (node->speed[1] > pSystem->velocity)
    node->speed[1] = pSystem->velocity;
else if (node->speed[1] < pSystem->nVelocity)
    node->speed[1] = pSystem->nVelocity;
if (node->speed[2] > pSystem->velocity)
    node->speed[2] = pSystem->velocity;
else if (node->speed[2] < pSystem->nVelocity)
    node->speed[2] = pSystem->nVelocity; 

没有有意义的方法来对比较进行switch,但我会重写这样的东西(假设你在第一行中的"系统"实际上应该是"pSystem"):

int clamp(int x, int min, int max)
{
    if (x < min)
        return min;
    if (x > max)
        return max;
    return x;
}
for (int i = 0; i<3 ; ++i)
  node->speed[i] = clamp(node->speed[i], pSystem->nVelocity, pSystem->velocity);

旁注:看起来您已经切换了"速度"和"速度"的含义。
速度是一个矢量,具有方向和大小,而速度是一个标量 - 速度的大小。

它实际上不适合开关语句,但适合 for 循环。

for (int i = 0; i<3 ; ++i)
  if (node->speed[i] > system->velocity)
     node->speed[i] = pSystem->velocity;
  else if (node->speed[i] < pSystem->nVelocity)
     node->speed[i] = pSystem->nVelocity;