如何将 if 语句更改为开关
how to change an if statement to a switch
如何将以下代码从 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;
相关文章:
- C 和 C++ 中开关语句的案例标签的常量值,但显示不同的行为
- 为什么布尔开关语句有编译器警告?
- 如何使用"equal to"以外的评估编写开关语句
- 有没有办法在C++将字符串与开关语句一起使用?
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- C++实用程序,用于将长开关语句转换为封装开关案例阶梯的简洁函数调用
- 如何循环开关语句直到找到所需的数字?
- 带有关闭/打开布尔值的开关语句
- 清理开关语句
- 我的开关语句在C++中不起作用
- 枚举和开关语句C++
- 如何在开关语句中使用 cin "as a parameter"
- "constexpr if"比开关语句好吗?
- C++ 默认值在开关语句中不起作用
- 初学者C :为什么此开关语句给我一个错误
- C 开关语句无法正常工作
- 为什么允许在开关语句中声明变量?但不是声明 初始化
- 根据数据包类型更改行为,避免开关语句
- 如何在开关语句(C )内或外部使用IF语句
- 使用开关语句案例中的随机数