编程珠玑:第三章 数据决定程序结构 习题解答
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);
采用二分搜索定位到采用哪个分段函数,然后对应求出结果。
参考链接:http://blog.csdn.net/tianshuai1111/article/details/7560129
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
相关文章推荐
- Eclipse配置Javadoc
- LeetCode之Valid Anagram (Java+C/C++)
- Java finally语句到底是在return之前还是之后执行?
- spring in action 第4章
- C++多态实现原理详解
- 百度笔试编程题:最大子阵和(C++)
- 自定义ContentProvider
- Python异常处理
- 《笨办法学python》的本人答案,习题 26: 恭喜你,现在可以考试了!
- JVM(java 虚拟机)内存设置
- java字符串操作,验证输入的身份证合法与否
- java运行的问题
- 用PHP语言刷OJ题
- Java基础:多线程
- 百度笔试编程题:爬行的蚂蚁(c++)
- Day3.Java基础之构造方法,继承,多态...
- python学习之函数
- Eclipse或MyEclipse中给第三方jar包添加源码步骤
- Java-equals方法和==的使用
- spring in action 第3章