duplicates - C++ Calculating shipping cost based on weight -
part of program i'm working on implements function takes in package weight argument , calculates shipping cost based on weight. criteria cost/lb follows:
        package weight              cost         --------------              ----         25 lbs & under              $5.00 (flat rate)         26 - 50 lbs                 above rate + 0.10/lb on 25         50 + lbs                    above rate + 0.07/lb on 50   i used if-if else-if make calculations, feel bit repetitive:
const int tier_2_weight = 25; const int tier_3_weight = 50;  const float tier_1_rate = 5.00; const float tier_2_rate = 0.10; const float tier_3_rate = 0.07;  float shippricef;   if(shipweightf <= tier_2_weight) {     shippricef = tier_1_rate; } else if(shipweightf <= tier_3_weight) {     shippricef = ((shipweightf - tier_2_weight) * tier_2_rate) +                    tier_1_rate; } else {     shippricef = ((shipweightf - tier_3_weight) * tier_3_rate)   +                  ((tier_3_weight - tier_2_weight) * tier_2_rate) +                    tier_1_rate; }  return shippricef;   so, question is... best way accomplish task, or should looking different solution?
first @ all, code looks clear , ok is.
of course, deduplicate redundant parts of formulas using cumulative approach:
float shippricef = tier_1_rate; // paid anyway  if (shipweightf > tier_2_weight) // add tier 2 if necessary {     shippricef += (min(shipweightf, tier_3_weight) - tier_2_weight) * tier_2_rate; } if(shipweightf > tier_3_weight)  // add tier 3 if necessary {     shippricef += (shipweightf - tier_3_weight) * tier_3_rate); }   well, simplified further:
float shippricef = tier_1_rate                       + max(min(shipweightf,tier_3_weight)-tier_2_weight,0) * tier_2_rate                       + max(shipweightf-tier_3_weight,0) * tier_3_rate;    for 3 scales, it's ok synthetic formula. if want more flexibility however, think of iterating throug vector of rates instead of using constants. allow variable number of scales. if you're sure formula progressive (eg. "above + new unit price what's exceding") use cumulative approach.
Comments
Post a Comment