If-Else嵌套多余?

时间:2017-11-02 23:56:46

标签: c++ if-statement

目前,我正在当地大学学习C ++课程,并获得调试任务。在这个赋值的说明中,我被告知这个代码唯一真正错误的是,第82-89行的嵌套if-else-if语句的条件是多余的,但是,我看不到另一种获取方法没有这些条件保持不变的相同结果...任何提示或类似的将不胜感激!

MemoryMappedViewStream

2 个答案:

答案 0 :(得分:0)

这部分else if(numOfChecks >= MID_LIMIT && numOfChecks < HIGH_LIMIT)看起来多余。如果保持范围检查的顺序,它可以简化为else if (numOfChecks < HIGH_LIMIT),与后面的那个相同(只是不需要),这样整个部分看起来像:

//the following line runs only if the program did not terminate, so start over if-else
if (numOfChecks < LOW_LIMIT)
    multiplierValue = LOW_CHECKS;
else if (numOfChecks < MID_LIMIT)
    multiplierValue = MIDLOW_CHECKS;
else if (numOfChecks < HIGH_LIMIT)
    multiplierValue = MIDHIGH_CHECKS;
else
    multiplierValue = HIGH_CHECKS; 

答案 1 :(得分:0)

确实,所有条件都是多余的:使用算法:)

<强> Live On Coliru

#include <iomanip>
#include <map>
#include <iostream>

namespace {
    using Threshold = unsigned;
    using Rate      = double;

    static Rate constexpr BASE_COST = 10.0;

    std::map<Threshold, Rate, std::greater<> > const tariffs {
        { 0, .10},
        {20, .08},
        {40, .06},
        {60, .04},
    };

    double fee(unsigned numOfChecks) {
        auto rate = tariffs.lower_bound(numOfChecks);
        return BASE_COST + rate->second * numOfChecks;
    }
}

int main() {
    unsigned numOfChecks;
    std::cout << "Please enter the number of checks you used this month: ";

    if (std::cin >> numOfChecks) {
        std::cout 
            << "\nYour total for this month is $"
            << std::fixed << std::showpoint << std::setprecision(2) << fee(numOfChecks)
            << std::endl;
    } else {
        std::cout << "Invalid input\n";
        return 1;
    }
}

打印例如。

Please enter the number of checks you used this month: 10
Your total for this month is $11.00

Please enter the number of checks you used this month: 20
Your total for this month is $11.60

Please enter the number of checks you used this month: 30
Your total for this month is $12.40

Please enter the number of checks you used this month: 40
Your total for this month is $12.40

Please enter the number of checks you used this month: 50
Your total for this month is $13.00

Please enter the number of checks you used this month: 60
Your total for this month is $12.40

Please enter the number of checks you used this month: 70
Your total for this month is $12.80

Please enter the number of checks you used this month: 80
Your total for this month is $13.20

Please enter the number of checks you used this month: 90
Your total for this month is $13.60

Please enter the number of checks you used this month: 100
Your total for this month is $14.00