如何使用C++在没有多个if-else语句的情况下编写以下代码
How to write following code without multiple if-else-statements using C++?
以下是条件。如何在不使用多个if语句的情况下编写等效代码?
if ((direction >= 0 && direction <= 11.25) || (direction > 348.75 && direction <= 360)) {
Dir = "N";
} else if (direction > 11.25 && direction <= 33.75) {
Dir = "NNE";
} else if (direction > 33.75 && direction <= 56.25) {
Dir = "NE";
} else if (direction > 56.25 && direction <= 78.75) {
Dir = "ENE";
} else if (direction > 78.75 && direction <= 101.25) {
Dir = "E";
} else if (direction > 101.25 && direction <= 123.75) {
Dir = "ESE";
} else if (direction > 123.75 && direction <= 146.25) {
Dir = "SE";
} else if (direction > 146.25 && direction <= 168.75) {
Dir = "SSE";
} else if (direction > 168.75 && direction <= 191.25) {
Dir = "S";
} else if (direction > 191.25 && direction <= 213.75) {
Dir = "SSW";
} else if (direction > 213.75 && direction <= 236.25) {
Dir = "SW";
} else if (direction > 236.25 && direction <= 258.75) {
Dir = "WSW";
} else if (direction > 258.75 && direction <= 281.25) {
Dir = "W";
} else if (direction > 281.25 && direction <= 303.75) {
Dir = "WNW";
} else if (direction > 303.75 && direction <= 326.25) {
Dir = "NW";
} else if (direction > 326.25 && direction <= 348.75) {
Dir = "NNW";
编写该代码的一种方法是使用数组来保存所有字符串值,并使用一些魔术将direction
转换为该数组的索引:
const std::string Directions[16] =
{
"N", "NNE", "NE", "ENE", "E", "ESE", "SE", "SSE",
"S", "SSW", "SW", "WSW", "W", "WNW", "NW", "NNW"
}
// And now the magic to pick the appropriate element from the array
direction += 11.25;
if (direction >= 360.0)
direction -= 360.0;
direction /= 22.5;
Dir = Directions[static_cast<int>(direction)];
相关文章:
- 这个c++代码是如何在没有定义函数的情况下运行的
- 如何在没有函数的情况下编写此代码并使C++更简单?
- 在什么情况下,我想在 C/C++ 代码中使用内联汇编代码
- 可以在没有构建代码的情况下转到定义吗?
- 在没有引用传递资源的情况下,如何在java中简化这些代码
- 尝试在不使用转换概念的情况下呈现此代码
- 寻找有关为什么此C++代码在没有引用的情况下不起作用的解释
- 在运行时,何时完全初始化 std 库才能在不破坏代码的情况下使用它?
- 在存在错误代码的情况下输出参数与 NRVO
- 在给定相同的输入的情况下,某些代码怎么可能花费更多时间来运行,这似乎只是因为它处于循环中?
- 在链接的程序集文件中,我想从 c++ 调用代码访问变量.是否可以在不触发访问冲突的情况下执行此操作?
- 为什么我的代码在没有 chroot 函数的情况下工作,但使用 chroot 函数失败?
- 如何在不复制此代码的情况下将多个函数放入多个命名空间?
- 如何在 C++03 中没有重复代码的情况下在堆栈上创建一个非常量 C 字符串数组?
- 在没有额外代码的情况下链接两个独立类的最通用方法是什么?
- 如何在没有性能命中的情况下抽象SIMD代码来处理不同的数据类型
- 为什么 GCC 6.3 在没有显式 C++11 支持的情况下编译此大括号初始化列表代码
- 打包结构,而不是在没有代码重复的情况下打包
- 如何在不中断剩余代码的情况下仅C++中输入整数
- 如何在<typename> <long> 不更改给定代码的情况下将自定义向量与 STL 向量相互转换?