如何使用C ++编写以下代码而不使用多个if-else语句?

时间:2015-02-25 09:20:13

标签: 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";

1 个答案:

答案 0 :(得分:3)

编写该代码的一种方法是使用数组来保存所有字符串值,并使用一些魔法将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)];