如何减少 if 语句链?

How to I reduce a chain of if statements?

如何减少 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;
}

这是示例代码。

您可以使用整数除法以数学方式生成此值:

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));

类似于:

#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

对于数组,你可以这样做:

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

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

#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
}