编程珠玑之第三章习题1

问题描述:

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

1
2
3
4
5
6
7
8
9
10
11
12
13
if income <= 2200
    tax = 0
else if income < 2700
    tax =        .14 * (income - 2200)
else if income <= 3200
    tax = 70   +   .15 * (income - 2700)
else if income <= 3700
    tax = 145 +   .16 * (income - 2200)
else if income <= 4200
    tax = 225 +  .17 * (income - 2200)
.....
else 
   tax = 53090 + .70 * (income - 102200)

问题解析:

1、编程中有一条这样的经验,如果一段代码中有过多的if语句,那么就该考虑是否可以用一个通用的函数来代替。

2、本题只是让你给出一个具体的建议,并不要求编程实现。但对前面5钟费率到可以使用一个函数来替代,后面由于题意不明,不得而知!

解决方案:

方案1:对前5钟费率的一个通用函数,代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#include <iostream>
#include <cassert>
using namespace std;


int foo(int i)
{
    int k = i;
    if (i > 1) k += foo(i -1 );

    return k;
}

/************************************************************************/
// 函数名称:calculate_tax
// 函数目的:以收入计算个人所得税
// 函数参数:income 收入
// 函数返回:个人所得税
// 使用条件:income <= 4700
/************************************************************************/

float calculate_tax(int income)
{
    assert (income <= 4700);

    int tax = 0.0;
    if (income <= 2200)  return tax;

    int index = (income - 2200) / 500;
    int mod   = (income - 2200) % 500;
    if (mod == 0 && index != 1){ index -= 1; }

    tax = 65 * index + 5*foo(index) + 0.01 * (14 + index) * (income - 2200 - 500*index);

    cout << "打印当前税收的计算公式:" << endl;
    int val1 = 65 * index + 5*foo(index);
    float val2 = 0.01 * (14 + index);
    int vale3 = 2200 + 500*index;
    cout << val1 << "+" << val2 << " * (income -" << vale3 << ")" << endl;

    return tax;
}

int main()
{
    cout << "请输入工资收入(income):";
    int income;
    while (cin >> income){
        cout << "tax = " << calculate_tax(income) << endl;
        cout << "请输入工资收入(income):";
    }

    return 0;
}
输入结果如下:


心得疑惑;

1、有很多时候,只要多花一点思考,就能使哪些该死的代码变得精炼简洁!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值