In each of the options from your previous code example, savings is calculated with something like:
1 2 3
|
saving = receiptAmt * sDiscountAdd;
cout<<"You saved: $";
cout<<showpoint<<fixed<<setprecision(2)<<saving<<endl;
|
This is repeated in each of the clauses, but where the parameter "sDiscountAdd" is chosen differently, they're all otherwise the same. So, this is a typical pattern where a function is used to homogenize a control over the "saving" parameter, and it subsequently simplifies your code.
I assume floats, but use whatever "savings" really is (a double maybe, I'm not sure).
1 2 3 4 5 6 7 8 9 10 11
|
float calc_saving( float receiptAmt, float discount )
{
float s = receiptAmt * discount;
if ( s > 30 ) s = 30;
cout<<"You saved: $";
cout<<showpoint<<fixed<<setprecision(2)<<s<<endl;
return s;
}
|
Now, where each clause currently says something like the first example in this post, it can read:
saving = calc_saving( receiptAmt, sDiscountAdd );
Thus, the repeated code is now no longer repeated (all those couts in each clause), and the selection according to each case is handled by the parameter, which wraps the concept of "limiting" the value of saving into a function.