您的位置:首页 > 编程语言

编程珠玑:第三章 数据决定程序结构 习题解答

2016-09-13 21:44 459 查看
一.题目描述:本书出版之时,美国的个人收入所得税分为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);

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

#include <iostream>
using namespace std;

int basetax[100];
int lowerbound[100];
double taxrate[100];

int search(int lowerbound[],int income)
{
int i=0;
int j=99;
int t=(i+j)/2;

while(1)
{

if(income - lowerbound[t] < 500 && income - lowerbound[t] >=0)
return t;
else if(income - lowerbound[t] < 0) //在左侧寻找
{
j=t;
t=(i+j)/2;

}
else
{
i=t;
t=(i+j)/2;
}
}
return  -1;

}
int main()
{
basetax[0]=0;
lowerbound[0]=0;
taxrate[0]=0;

basetax[1]=0;
lowerbound[1]=2200;
taxrate[1]=0.14;

for(int i=2;i<100;++i)
{
basetax[i]=75*i-80;
lowerbound[i]=2200 + (i-1)*500;
taxrate[i]=(double)(14 + i-1)/100;

}

int salary;
<span style="white-space:pre">	</span>cout<<"please input salary:\n";
<span style="white-space:pre">	</span>cin>>salary;
int j=search(lowerbound,salary);

double tax= basetax[j] +   (double)taxrate[j]*(salary -lowerbound[j]);

cout<<tax<<endl;
}

return 0;
}


参考链接:http://blog.csdn.net/tianshuai1111/article/details/7560129
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: