使用什么来代替if/else、switch或三元运算符

what to use instead of if/else, switch or ternary operators?

本文关键字:switch 运算符 三元 else 什么 if      更新时间:2023-10-16

只是一个快速问题。我有一个学校项目,我必须作为一个新的单独问题再次解决这个问题。只使用一行代码,不使用任何if/else或switch语句,也不使用三元运算符来提供税收计算。我可能可以在一行代码中进行计算,但如果要去掉条件语句,我不知道该写什么。下面是我应该更改的代码。我的老师对我们能用什么和不能用什么有点挑剔。此外,这个项目是在我们还没有学习这些函数的时候给我们的。我正在寻找一个不太高级别的答案,因为我是c++的新手。/***************************************************************

为一个根据税率表计算税款的州编写一个程序:•前15000美元收入免税•15001美元至25000美元每美元征收5%的税•25000美元以上每美元征收10%的税***************************************************************/

   #include <iostream>
        #include <string>
        #include <sstream>
        #include <iomanip>
        using namespace std;
        int main()
        {
            string income2;
            double income;
            const double FIRSTTAX = 500;
            double secondDifference;
            const double FTAX = 0.05;
            const double TTAX = 0.1;
            cout << "Please enter the annual income: $ ";
            getline (cin, income2);
            stringstream (income2)>> income;

                if (income == 0 || income <= 15000 )
                {
                    cout << "No income on first 15000 " << endl;
                }
            else if (income > 15000 && income <= 25000)
                {
                    income = (income - 15000)* FTAX;
                    cout << " Your net income " << income <<endl;
                }
             else if (income > 25000)
                {
                    secondDifference = (income - 25000) * TTAX +(income - 15000- (income - 25000)) * FTAX;

                    cout << " Your net income " << income <<fixed<<setprecision(2) <<endl;
                    cout << " Your tax " << secondDifference <<fixed<<setprecision(2) << endl;
}


        return 0;
    }

在一行中:

tax = max(income-15000,0)*FTAX + max(income-25000,0)*(TTAX-FTAX)

考虑两种不同的税率,并允许任何一种税率单独变化:

double lo_thresh = 15000;
double hi_thresh = 25000;
double lo_rate = 0.05;
double hi_rate = 0.10;
double tax = lo_rate * min(hi_thresh - lo_thresh, max(income - lo_thresh, 0)) +
             hi_rate * max(income - hi_thresh, 0);

上半年的收入超过15000,但将超过该金额的金额上限为10000(即两个阈值之间的差额)。

下半年计算的是收入超过25000的更高税率。