习题3.7.1——二分法解决美国税率问题

题目描述

本书行将出版之时,美国的个人收入所得税分为5种不同的税率,其中最大的税率大约为40%。以前的情况则更为复杂,税率也更高。下面所示的程序文本采用25个if语句的合理方法来计算1978年的美国联邦所得税。税率序列为0.14, 0.15, 0.16, 0.17, 0.18,.....。序列中此后的增幅大于0.01。有何建议呢?

if income <= 2200
    tax = 0;
else if income <= 2700
    tax = 0.14 * (income - 2200);
else if income <= 3200
    tax = 70 + 0.15 * (income - 2700);
else if income <= 3700
    tax = 145 + 0.16 * (income -3200);
else if income <= 4200
    tax = 225 + 0.17 * (income - 3700);
.......
else
    tax = 53090 + 0.70 * (income - 102200);

解决思路

采用二分搜索定位到采用分段函数,然后求出对应结果。

不过对于题目的「序列中此后的增幅大于0.01」不是很明确其含义。

#include <iostream>
using namespace std;

float BaseTax[100];
int LevelIncome[100];
float TaxRate[100];

int search(int LevelIncome[], int Income)
{
    int i = 0;
    int j = 99;
    int t = (i + j) / 2;
    
    while (1)
    {
        if (Income - LevelIncome[t] < 500 && Income - LevelIncome[t] >= 0)
            return t;
        else if (Income - LevelIncome[t] < 0)
        {
            j = t;
            t = (i + j) / 2;
        }
        else
        {
            i = t;
            t = (i + j) / 2;
        }
    }
    
    return -1;
}

int main()
{
    BaseTax[0] = 0;
    LevelIncome[0] = 0;
    TaxRate[0] = 0;

    BaseTax[1] = 0;
    LevelIncome[1] = 2200;
    TaxRate[1] = 0.14;

    for (int i = 2; i < 100; i++)
    {
        TaxRate[i] = (float)(14 + i - 1) / 100;
        TaxRate[i] = (int)(TaxRate[i] * 100 + 0.5) / 100.0;
        LevelIncome[i] = 2200 + (i - 1) * 500;
    }
    
    for (int i = 1; i < 100; i++)
    {
        BaseTax[i] = BaseTax[i - 1] + TaxRate[i] * (LevelIncome[i + 1] - LevelIncome[i]);
    }

    int salary = 4000;
    int j = search(LevelIncome, salary);
    double tax = BaseTax[j - 1] + TaxRate[j] * (salary - LevelIncome[j]);
    
    cout << tax << endl;
    
    system("pause");
    return 0;
}
发布于: 2013-06-21