程式設計珠璣:第三章 資料決定程式結構 習題解答
阿新 • • 發佈:2018-12-25
一.題目描述:本書出版之時,美國的個人收入所得稅分為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