Better way? ...again ;)

Fee per person based on number of people.
1-4 \$100 per
5-10 \$80 per
11 <= \$60 per

Just wondering if there is a more efficient way to do this. Would it be better to put the 'cout << "Invalid number of people";' in the if statement? Or leaving it in the switch statement good practice?

Thanks again!!!

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061`` ``````// Ch6Ex13.cpp - Display the amount a company // owes for a seminar based on number of people registered // Created by 12 Sept 2012 #include #include using namespace std; int main() { // Declare variables int numPeople = 0; int caseNum = 0; double amtOwed = 0.0; // Enter Input cout << "Number Registered: "; cin >> numPeople; // Determind valid number of people if (numPeople >= 1 && numPeople <= 4) { caseNum = 1; } else if (numPeople >= 5 && numPeople <= 10) { caseNum = 2; } else if (numPeople >= 11) { caseNum = 3; } //end if // Determine Amount Owed switch(caseNum) { case 1: amtOwed = numPeople * 100; cout << fixed << setprecision(2); cout << "Amount Owed: \$" << amtOwed; break; case 2: amtOwed = numPeople * 80; cout << fixed << setprecision(2); cout << "Amount Owed: \$" << amtOwed; break; case 3: amtOwed = numPeople * 60; cout << fixed << setprecision(2); cout << "Amount Owed: \$" << amtOwed; break; default: cout << "Invalid Number of People."; break; } // End Switch cout << endl; //system("pause") return 0; } // End of main function ``````
Leaving it in the switch statement is the best because it makes the work easier and also makes the code look simple.
You can declare a double array caseRates[3] to hold the rate for each case.

 ``1234567891011121314`` ``````double caseRates[3] = {100, 80, 60}; ... if (caseNum > 0 && caseNum <= 3) { amtOwed = numPeople * caseRates[caseNum - 1]; cout << fixed << setprecision(2); cout << "Amount Owed: \$" << amtOwed; } else { cout << "Invalid Number of People."; }``````
Appreciate the responses. I'm not that far into C++, don't really know about double arrays.

why `[caseNum - 1]`? Why is there a subtraction?

Again thanks for the responses. I won't be using double array due it being a school assignment, but still interested on how it works.
Last edited on
caseRates maps caseNum to the appropriate caseRate. (1->100, 2->80, 3->60)

Because caseRates hold maximum 3 values, index 0,1,2, so if you want to use caseRates[caseNum - 1], first you have to check if (caseNum-1) is in range [0,2], which means caseNum is in range [1,3].

Last edited on
I see, thanks!! Appreciate it.
Topic archived. No new replies allowed.