如何减少if语句链?

时间:2015-09-12 15:07:37

标签: c++ if-statement numbers

如何在C ++中减少if语句链?

if(x == 3) {
    a = 9876543;
}
if(x == 4) {
    a = 987654;
}
if(x == 5) {
    a = 98765;
}
if(x == 6) {
    a = 9876;
}
if(x == 7) {
    a = 987;
}
if(x == 8) {
    a = 98;
}
if(x == 9) {
    a = 9;
}

这是示例代码。

4 个答案:

答案 0 :(得分:8)

您可以使用整数除法在数学上生成此值:

long long orig = 9876543000;
long long a = orig / ((long) pow (10, x));

编辑:
正如@LogicStuff在评论中指出的那样,从x中减去3会更加优雅,而不是仅仅将orig乘以另一个1000

long orig = 9876543;
long a = orig / ((long) pow (10, x - 3));

答案 1 :(得分:4)

使用数组,您可以:

if (3 <= x && x <= 9) {
    const int v[] = {9876543, 987654, 98765, 9876, 987, 98, 9};
    a = v[x - 3];
}

答案 2 :(得分:1)

类似的东西:

#include <iostream>
#include <string>

int main() {
    int x = 4;
    int a = 0;
    std::string total;
    for(int i = 9; i > 0 ; --i)
    {
        if(x <= i)
          total += std::to_string(i);
    }
    a = std::stoi(total, nullptr);
    std::cout << a << std::endl;
    return 0;
}

http://ideone.com/2Cdve1

答案 3 :(得分:1)

如果可以推导出数据,我建议使用其他答案之一 如果您意识到它们是一些边缘情况,最终导致派生更复杂,请考虑一个简单的查找表。

#include <iostream>
#include <unordered_map>

static const std::unordered_multimap<int,int> TABLE
{{3,9876543}
,{4,987654}
,{5,98765}
,{6,9876}
,{7,987}
,{8,98}
,{9,9}};

int XtoA(int x){

    int a{0};
    auto found = TABLE.find(x);
    if (found != TABLE.end()){
        a = found->second;
    }

    return a;
}

int main(){

    std::cout << XtoA(6) << '\n'; //prints: 9876
}
相关问题