编程珠玑第三章习题1

问题:

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 =        .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)
参考代码:
// Pearls3_1.cpp : Defines the entry point for the console application.
//编程珠玑第二版 习题3.1
//主要思路:用一个表来保存税收所有的税率选项,表的每一项包含三部分:该等级的下界,基本税收,超出下界的税率
//然后根据公式计算出工资属于表的第几项,再根据项中的税率选项计算出应缴的税

#include "stdafx.h"
#include
#include
#define N 5

using namespace std;

struct tax{
	double bound;//该等级的下界
	double base;//基本税收
	double rate;//超出下界的税率
};

tax taxTable[N];

void CreateTable()//构建税收表
{
	taxTable[0].bound = 0;
	taxTable[0].base = 0;
	taxTable[0].rate = 0;
	taxTable[1].bound = 2200;
	taxTable[1].base = 0;
	taxTable[1].rate = 0.14;
	for (int i = 2; i < N; ++i)
	{
		taxTable[i].bound = taxTable[i - 1].bound + 500;
		taxTable[i].rate = taxTable[i - 1].rate + 0.01;
		taxTable[i].base = taxTable[i - 1].base + taxTable[i - 1].rate * 500;
	}
}

double calculate_tax(double income)
{
	assert(income <= 4200);
	int index = (income - 2200+500-1) / 500;
	cout << "打印当前的计算公式:" << endl;
	cout << taxTable[index].base << " + " << taxTable[index].rate << " * (income - " << taxTable[index].bound << ")" << endl;
	return taxTable[index].base + taxTable[index].rate*(income - taxTable[index].bound);
}
int _tmain(int argc, _TCHAR* argv[])
{
	CreateTable();
	cout << "请输入工资收入(income):";
	int income;
	while (cin >> income){
		cout << "tax = " << calculate_tax(income) << endl;
		cout << "请输入工资收入(income):";
	}

	return 0;
	return 0;
}

参考:
http://blog.csdn.net/johnnyhu90/article/details/42710505

你可能感兴趣的:(算法)