使用 switch 语句的替代方案 C++ [已关闭]

问题描述 投票:0回答:1

我的

switch
声明中有大约 40 个案例。它检查的值是一个由用户的两个输入连接而成的数字,因此如果他们输入 3 和 4,则会将 34 传递给
switch
语句。每个
switch
语句都会将该值传递给另一个函数,然后该函数根据连接的值返回素材长度。有什么更好的方法来做到这一点?

我正在考虑某种数组,我可以

for
循环查找我想要的值?

编辑:代码片段

void calcFootages2(const int z) {
    std::cout << "\n\nThe value of Z: " << z;
    switch (z) {
        default:
            std::cout << "\nYour input of " << z << " was invalid or something went wrong, please retry.";
            locChoose();
            break;
        case (12):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (21):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (23):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (32):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
        case (34):
            std::cout << "\nThis will require a jumper " << calcFootages3(z) << " feet long.";
            break;
    }
}

calcfootages 功能 -

int calcFootages3(const int x) {
        if (x == 12 || x == 21) {
            return 10;
        }
        else if (x == 23 || x == 32) {
            return 11;
        }
    }

因此 return 11 最终将是正确的素材长度,然后将其传递回 switch 语句,以便它可以将其显示给用户。我拿走了大部分的陈述,因为它们几乎都是一样的。

我希望我的代码格式正确。

c++ arrays switch-statement
1个回答
4
投票

您可以将有效规格的检查和素材计算分开,例如像这样:

std::vector<int> const valid_spec = {12, 21, 23, 32, 34};

if( find( valid_spec.begin(), valid_spec.end(), z ) == valid_spec.end() )
{
    cout << "Your input of " << z << " was invalid or something went wrong, please retry.";
}
else
{
    cout << "This will require a jumper " << calcFootages3(z) << " feet long.";
}
© www.soinside.com 2019 - 2024. All rights reserved.