C++ 个人所得税计算

1. 问题描述

工资计算本质上就是分段函数,思想很简单。

2. 代码实现

采用C++语言,代码出自Smart-C++常用代码库:

#include 
    
     

double sal2tax(double salary) {
    salary -= 2000;
    double tax = 0;
    double sal[][2] = {
        {0, 0.05},
        {500, 0.1},
        {2000, 0.15},
        {5000, 0.2},
        {20000, 0.25},
        {40000, 0.3},
        {60000, 0.35},
        {80000, 0.4},
        {100000, 0.45}
    };

    for(int i = 0; i < 8; ++i) {
        if(salary < sal[i][0])break;

        double t = ((salary - sal[i][0]) > (sal[i + 1][0] - sal[i][0]) ?
                    (sal[i + 1][0] - sal[i][0]) : (salary - sal[i][0])) * sal[i][1];
        tax += t;
    }

    return tax;
}

double tax2sal(double tax) {
    double sal_h = 80000;
    double sal_l = 0;

    while(sal_h > sal_l) {
        double mid = sal_h + sal_l;
        mid /= 2;

        if(sal2tax(mid) > tax) {
            sal_h = mid - 1;
        } else if(sal2tax(mid) < tax) {
            sal_l = mid + 1;
        } else {
            sal_l = mid;
            break;
        }
    }

    return sal_l;
}

int main() {
    double salary;

    while(1) {
        printf("---------------------\n"
               "1. from salary to tax\n"
               "2. from tax to salary\n"
               "---------------------\n"
              );
        int c;

        do {
            scanf("%d", &c);
        } while(c != 1 && c != 2);

        if(c == 1) {
            fprintf(stderr, "salary = ");
            scanf("%lf", &salary);
            printf("%lf\n", sal2tax(salary));
        } else {
            fprintf(stderr, "tax = ");
            scanf("%lf", &salary);
            printf("%lf\n", tax2sal(salary));
        }
    }
}

    

3. 注意事项

1. 二维数组的使用

sal2tax函数采用二维数组,循环累加,缩减代码量。

double sal[][2] = {
    {0, 0.05},
    {500, 0.1},
    {2000, 0.15},
    {5000, 0.2},
    {20000, 0.25},
    {40000, 0.3},
    {60000, 0.35},
    {80000, 0.4},
    {100000, 0.45}
};

2. 二分法

tax2sal函数采用二分法,提高效率。

 while(sal_h > sal_l) {
    double mid = sal_h + sal_l;
    mid /= 2;

    if(sal2tax(mid) > tax) {
        sal_h = mid - 1;
    } else if(sal2tax(mid) < tax) {
        sal_l = mid + 1;
    } else {
        sal_l = mid;
        break;
    }
}

3. 数据类型选择

数据类型的选择要实事求是。在上一篇博客里面,针对CCF_CSP 201612-02题中对数据的限制很宽松,我主要采用的数据类型int。

int salary;//整数
double salary;//有效数字16位

你可能感兴趣的:(C++ 个人所得税计算)