如何使用C++在没有多个if-else语句的情况下编写以下代码

How to write following code without multiple if-else-statements using C++?

本文关键字:情况下 代码 语句 if-else C++ 何使用      更新时间:2023-10-16

以下是条件。如何在不使用多个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)];
相关文章: