Charles,
If I order 4.5 lbs of coffee your code gives no output. To avoid this sort of problem, it's best to use a ladder like this:
1 2 3 4 5 6 7
|
if (pounds_wanted < 0.0) {
cout << "Purchase amount cannot be negative\n";
} else if (pounds_wanted < 5.0) {
// full price
} else if (pounds_wanted < 10.0) {
// 5% discount
} etc.
|
Alternatively, if coffee can only be purchased in whole pounds, then pounds_wanted should be an
int
or
unsigned
.
1 2 3 4
|
double firstlevel = 0.05;
double secondlevel = 0.10;
double thirdlevel = 0.15;
double fourthlevel = 0.20;
|
Any time you see yourself writing variables like first, second, third, or foobar1, foobar2, foobar3, you should think of converting it to an array.
Also, as a general rule of thumb,
data is smaller and faster than
code. Putting these together, it makes sense to put the discount levels and amounts into a small table.
Also, keep in mind that the data that's convenient for the
user is not necessarily the data that's convenient for the
program. In this case, it's better for the program to store the
price rate, rather than the
discount rate:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include <iostream>
// #include <string> // not needed
#include <iomanip>
using namespace std;
struct Price {
double ceiling; // The purchase amount must be less
// than this to get this rate
double rate; // price per pound at this level
};
// The price rates, ordered by the ceiling amount. Note that this
// stores the actual price rate, which is (1 - discount)
Price rates[] = {
{ 5.0, 1.0 - 0.00 }, // No discount on amounts below 5
{ 10.0, 1.0 - 0.05 }, // 5% discount below 10
{ 20.0, 1.0 - 0.10 },
{ 30.0, 1.0 - 0.10 },
{ 1E99, 1.0 - 0.20 }, // 20% discount up to huge number
{ -1, -1 }, // end of table
};
//main function
int main() {
double total_purchase_cost, pounds_wanted;
double retail_rate = 12.99; // full retail rate
cout << "How many pounds of coffee do you want to buy? " << endl;
cin >> pounds_wanted;
//calculations
// Go through the rates table. When you find the rate for this
// quantity, compute the total code and break out of the loop.
// This assumes that the rates are in increasing order of quantity
// and that the table ends with a negative rate
for (unsigned i = 0; rates[i].rate >= 0; ++i) {
if (pounds_wanted < rates[i].ceiling) {
total_purchase_cost = pounds_wanted * rates[i].rate * retail_rate;
break;
}
}
std::cout << std::fixed << std::setprecision(2);
cout << "Your final total is $ " << total_purchase_cost << endl;
return 0;
}
|