User - Defined Functions
The cost to become a member of a fitness center is as follows:
The senior citizens discount is 30%.
If the membership is bought and paid for 12 or more months, the discount is 15%
If more than five personal training sessions are bought and paid for, the discount on each session is 20%.
Write a menu-driven program that determines the cost of a new membership. Your program must contain a function that displays the general information about the fitness center and its charges, a function to get all of the necessary information to determine the membership cost, and a function to determine the membership cost. Use appropriate parameters to pass information in and out of a function. (Do not use any global variables.)
My codes:
#include <iostream>
#include <iomanip>
using namespace std;
// program constants
void setPrices(double&, double&);
void getInfo(bool&, bool&, bool&, int&, int&);
double membershipCost(double, int, double, int, bool, bool, bool);
void displayCenterInfo();
int main()
{
bool seniorCitizen;
bool boughtFiveOrMoreSessions;
bool paidTwelveOrMoreMonths;
int numberOfMembershipMonths;
int numberOfPersonalTrainingSessions;
double regularMembershipChargesPerMonth;
double costOfOnePersonalTrainingSession;
double memberCost;
cout << fixed << showpoint << setprecision(2);
displayCenterInfo();
cout << endl;
setPrices(regularMembershipChargesPerMonth, costOfOnePersonalTrainingSession);
getInfo(seniorCitizen, boughtFiveOrMoreSessions, paidTwelveOrMoreMonths, numberOfMembershipMonths, numberOfPersonalTrainingSessions);
// cal getInfo
memberCost = membershipCost(regularMembershipChargesPerMonth, numberOfMembershipMonths, costOfOnePersonalTrainingSession,
numberOfPersonalTrainingSessions, seniorCitizen, boughtFiveOrMoreSessions, paidTwelveOrMoreMonths);
cout << "$" << memberCost;
system("pause");
return 0;
}
void displayCenterInfo()
{
cout << "Welcome to Stay Healty and Fit center." << endl;
cout << "This program determines the cost of a new membership." << endl;
cout << "If you are a senior citizen, then the discount is 30% of "
<< "of the regular membership price." << endl;
cout << "If you buy membership for twelve months and pay today, the "
<< "discount is 15%." << endl;
cout << "If you buy and pay for 6 or more personal training session today, "
<< "the discount on each session is 20%." << endl;
}
void setPrices(double& regMemPrice, double& personalTrSesCost)
{
cout << "Please enter the cost of regular Membership per month: " << endl;
cin >> regMemPrice;
cout << "Please enter the cost of one personal traning session: " << endl;
cin >> personalTrSesCost;
}
void getInfo(bool& senCitizen, bool& bFiveOrMoreSess, bool& paidTwMnth,
int& nOfMonths, int& nOfPersonalTrSess)
{
//Senior Verification
char userInputSenior;
cout << "Are you Senior? Please enter 'Y' or 'N': ";
cin >> userInputSenior;
if (userInputSenior == 'y' && userInputSenior == 'Y')
{
senCitizen = true;
}
else
senCitizen = false;
cout << endl;
//Number of personal training session.
cout << "Enter the number of personal training sessions bought: ";
cin >> nOfPersonalTrSess;
if (nOfPersonalTrSess >= 5)
{
bFiveOrMoreSess = true;
}
else
bFiveOrMoreSess = false;
cout << endl;
//Number of months
cout << "Enter the number of months you are paying for: ";
cin >> nOfMonths;
if (nOfMonths >= 12)
{
paidTwMnth = true;
}
else
paidTwMnth = false;
}
double membershipCost(double regMemPricePerMth, int nOfMonths,
double personalTrSesCost, int nOfPersonalTrSess,
bool senCitizen, bool bFiveOrMoreSess, bool paidTwMnth)
{
double finalMembershipCost, finalSessionCost;
//Session Discount
if (bFiveOrMoreSess)
{
personalTrSesCost = personalTrSesCost * 0.8;
}
else
{
personalTrSesCost = personalTrSesCost;
}
//Month Discount
if (paidTwMnth)
{
regMemPricePerMth = regMemPricePerMth * 0.85;
}
else
{
regMemPricePerMth = regMemPricePerMth;
}
finalMembershipCost = regMemPricePerMth * nOfMonths;
finalSessionCost = personalTrSesCost * nOfPersonalTrSess;
// Check if Senior Citizen Discount Applies
if (senCitizen) {
return (finalMembershipCost * 0.7) + finalSessionCost ;
}
else {
return finalMembershipCost + finalSessionCost;
}
}
My Test Result
An error occurs on "Senior Citizen Discount".
Green color - My output.
Red color - Its output (Correct Answer).
I don't know how to get that answer ($2260.00) with my code. I have checked many times and I couldn't solve the problem. Please help me!
You should use an or-Statement for detecting if its a senior citizen:
if (userInputSenior == 'y' || userInputSenior == 'Y')
BTW: You have another small bug when calculating the discount for personal lessons, you only get a discount for more than 5 sessions, so the corresponding if-statement should be
(nOfPersonalTrSess > 5)
Thank you guys so much, I solved my problem!
Here is my complete program:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// program constants
void setPrices(double&, double&);
void getInfo(bool&, bool&, bool&, int&, int&);
double membershipCost(double, int, double, int, bool, bool, bool);
void displayCenterInfo();
int main()
{
bool seniorCitizen;
bool boughtSixOrMoreSessions;
bool paidTwelveOrMoreMonths;
int numberOfMembershipMonths;
int numberOfPersonalTrainingSessions;
double regularMembershipChargesPerMonth;
double costOfOnePersonalTrainingSession;
double memberCost;
cout << fixed << showpoint << setprecision(2);
displayCenterInfo();
cout << endl;
setPrices(regularMembershipChargesPerMonth, costOfOnePersonalTrainingSession);
getInfo(seniorCitizen, boughtSixOrMoreSessions, paidTwelveOrMoreMonths, numberOfMembershipMonths, numberOfPersonalTrainingSessions);
// cal getInfo
memberCost = membershipCost(regularMembershipChargesPerMonth, numberOfMembershipMonths, costOfOnePersonalTrainingSession,
numberOfPersonalTrainingSessions, seniorCitizen, boughtSixOrMoreSessions, paidTwelveOrMoreMonths);
cout << "$" << memberCost;
system("pause");
return 0;
}
void displayCenterInfo()
{
cout << "Welcome to Stay Healty and Fit center." << endl;
cout << "This program determines the cost of a new membership." << endl;
cout << "If you are a senior citizen, then the discount is 30% of "
<< "of the regular membership price." << endl;
cout << "If you buy membership for twelve months and pay today, the "
<< "discount is 15%." << endl;
cout << "If you buy and pay for 6 or more personal training session today, "
<< "the discount on each session is 20%." << endl;
}
void setPrices(double& regMemPrice, double& personalTrSesCost)
{
cout << "Please enter the cost of regular Membership per month: " << endl;
cin >> regMemPrice;
cout << "Please enter the cost of one personal traning session: " << endl;
cin >> personalTrSesCost;
}
void getInfo(bool& senCitizen, bool& bSixOrMoreSess, bool& paidTwMnth,
int& nOfMonths, int& nOfPersonalTrSess)
{
//Senior Verification
char userInputSenior;
cout << "Are you Senior? Please enter 'Y' or 'N': ";
cin >> userInputSenior;
if (userInputSenior == 'y' || userInputSenior == 'Y')
{
senCitizen = true;
}
else
senCitizen = false;
cout << endl;
//Number of personal training session.
cout << "Enter the number of personal training sessions bought: ";
cin >> nOfPersonalTrSess;
if (nOfPersonalTrSess > 5)
{
bSixOrMoreSess = true;
}
else
bSixOrMoreSess = false;
cout << endl;
//Number of months
cout << "Enter the number of months you are paying for: ";
cin >> nOfMonths;
if (nOfMonths >= 12)
{
paidTwMnth = true;
}
else
paidTwMnth = false;
}
double membershipCost(double regMemPricePerMth, int nOfMonths,
double personalTrSesCost, int nOfPersonalTrSess,
bool senCitizen, bool bSixOrMoreSess, bool paidTwMnth)
{
double finalMembershipCost, finalSessionCost;
//Session Discount
if (bSixOrMoreSess)
{
personalTrSesCost = (personalTrSesCost * 0.8);
}
else
{
personalTrSesCost = personalTrSesCost;
}
//Month Discount
if (paidTwMnth)
{
regMemPricePerMth = regMemPricePerMth * 0.85;
}
else
{
regMemPricePerMth = regMemPricePerMth;
}
finalMembershipCost = regMemPricePerMth * nOfMonths;
finalSessionCost = personalTrSesCost * nOfPersonalTrSess;
// Check if Senior Citizen Discount Applies
if (senCitizen) {
return (finalMembershipCost * 0.7) + finalSessionCost;
}
else {
return finalMembershipCost + finalSessionCost;
}
}
Related
I need help. I'm currently learning C++ programming and I'm still at the beginner level. I'm still figuring out how to make the while loop working. My idea is when inserting the correct code input, the switch statement choose the right case statement and loop back to insert another input until 0 inserted to stop the loop and calculate for the final output in main() constructor.
I know I have few kinks to fix soon but I'm still struggling to figure out this particular part.
#include <stdio.h>
#include <iostream>
#include <iomanip>
using namespace std;
double sst = 0.06, total = 0, grandTotal, price, discount, newPrice, totalSST;
int quantity, count, code;
string name, ech;
void item001(){
name = "Rice (5kg)";
price = 11.5;
discount = 0;
}
void item002(){
name = "Rice (10kg)";
price = 25.9;
discount = 0;
}
void item003(){
name = "Sugar (1kg)";
price = 2.95;
discount = 0;
}
void item_cal(){
cout << "Please enter the quantity of the item: ";
cin >> quantity;
newPrice = (price + (discount * price)) * quantity;
cout << "\nItem: " << name << " || Quantity: " << quantity << " || Price: RM" << newPrice << endl;
}
void input(){
cout << "Welcome SA Mart\n" << "Please insert the code. Press 0 to stop: ";
while (code != 0){
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
}
}
}
int main(){
input();
totalSST = total * sst;
grandTotal = total + totalSST;
cout << fixed << setprecision(2);
cout << "Total: RM" << total << " ||SST: RM" << totalSST << " || Grand Total: RM" << grandTotal << endl;
return 0;
}
The only functional issue I see in your code is that there is a chance that the code variable will initialize to 0 (depends on the compiler/randomness). If that happens, your input method will return before it enters the loop. Other than that it looks like it will work. Of course, programming is not just the art of "making it work," style and readability are important too. In general, you want to confine variables to the smallest scope in which they are referenced. 'code' should not be a global variable, it should live in the input method. As for the loop, there are several ways it could be implemented: a "while(true)" loop could be used, in which case the variable may be defined inside the loop; on the other hand a "do while" would guarantee one loop runs (perhaps that would be a good fit here), but the variable must live outside of the loop, at least int the scope of conditional check. The way you choose is often a matter of style. Below, I use a "while(true)."
In programming, readability matters (a lot). I think this program would be easier to read if the data were broken up into a few structs, perhaps "Bill," and "Food." Another thing to consider is how to broaden the usage of your program, without introducing significant complexity. For example, it could work for any grocery store (any set of food items/prices). This is often a matter of determining an appropriate set of parameters to feed your program.
To do these things you might write something like this:
#pragma once
#include <string>
#include <map>
using namespace std;
namespace market {
const double& sst = 0.06;
struct Bill {
double total = 0;
double totalSST = 0;
double grandTotal = 0;
};
struct Food {
const char* name;
double price;
double discount;
Food(const char* name, double price, double discount = 0)
: name(name), price(price), discount(discount) {}
double result_price() const {
return price - price * discount;
}
};
struct GroceryStore {
const char* name;
std::map<int, Food> inventory;
GroceryStore(const char* name, std::map<int, Food> inventory)
: name(name), inventory(inventory) { }
};
void shop(const GroceryStore& store, Bill& bill, bool show_menu = false, int exit_code = 0) {
// check error conditions
if (store.inventory.find(exit_code) != store.inventory.end()) {
// that's the 'exit_code' code silly!
cout << "Bad store. Come back another time." << endl;
return;
}
cout << "Welcome to " << store.name << endl;
if (show_menu) {
cout << "The following items are available for purchase:" << endl;
for (auto p : store.inventory) {
cout << "\t" << p.first << ") " << p.second.name << "(" << p.second.result_price() << endl;
}
}
cout << "Enter the product code of the item you wish to purchase:";
int code;
cin >> code;
while (true) {
auto food_it = store.inventory.find(code);
if (food_it == store.inventory.end()) {
cout << "Thanks for stopping by." << endl;;
break;
}
cout << "Please enter the quantity of the item: ";
uint32_t quantity;
cin >> quantity;
auto& food = food_it->second;
auto disc_price = food.price - (food.discount * food.price);
bill.total += disc_price * quantity;
cout << "\nItem: " << food.name << " || Quantity: " << quantity << " || Price: RM" << disc_price << endl;
cout << "Would you like anything else? Enter the product code, or press " << exit_code << " to proceed to check-out." << endl;
cin >> code;
}
}
void ring_up(Bill& bill) {
bill.totalSST = bill.total * sst;
bill.grandTotal = bill.total + bill.totalSST;
}
void run() {
int code = 1;
GroceryStore store("SMart", {
{ code++, Food("Rice (5kg)", 11.5, 0) },
{ code++, Food("Rice (10kg)", 25.9) },
{ code, Food("Sugar (1kg)", 2.95, 0) }
});
Bill bill;
shop(store, bill, true);
ring_up(bill);
cout << "Total: RM" << bill.total << " ||SST: RM" << bill.totalSST << " || Grand Total: RM" << bill.grandTotal << endl;
}
}
Firstly there is a bug in input when u will input 0 then also it won't break while loop as code that is checked contains the previous value.
for example:
input is
3
0
but according to your code when the code will run the second time and while condition is checked code still contains 3 as value and code will run one more time
Try initialising code to some value, for example, -1. I'm not really sure but I think for global int variables, they initialise int variables to 0. So your first loop doesn't run. Or another way to do it is using do while loops instead of while loop.
do {
cin >> code;
switch (code){
case 001:
item001();
item_cal();
break;
case 002:
item002();
item_cal();
break;
case 003:
item003();
item_cal();
break;
default:
cout << "\nWrong code" << endl;;
break;
total += newPrice;
} while (code != 0);
}
This makes sure that the loop will run at least once, making code initialised.
Hope it helps you! Have fun programming!
I'm writing a program for my C++ class I've complete the program. but it won't compile. I'm new to programming so I don't really know what I'm doing wrong. If there is anyone on here that can point me in the right direction. Please help me!
Prompt Description:
Write a C++ program to calculate free estimate for carpet and furniture cleaning of residential and business customers. The program continues until end of file is reached.
Fro residential customers, specify and update number of small couches ($50 each), large couches ($80 each), rooms ($70 each) and steps ($5 each) until exit is selected. the bill is calculated based on the number of items. If the amount is more than 500 dollars, a discount of 10% is applied to the bill. Then the customer is offered to select from an installment of 1,2,3, or 4 or press 0 to exit. Based on an installment option, the bill is increased slightlenter code herey, and each installment amount is calculated.
For business customers, ask the user to enter the amount of square footage and then the bill is calculated at .45 per square foot.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int exit = 0;
int smallcouches = 1;
int largecouches = 2;
int rooms = 3;
int steps = 4;
const float SMALL_COUCH = 50.0;
const float LARGE_COUCH = 80.0;
const float ROOMS = 70.0;
const float STEPS = 5.00;
const float PER_SQUARE_FOOT = 0.45f;
const float DISCOUNT_QUALIFIED = 500.0;
const float DISCOUNT = 0.10f;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const float RATEONE = 0.0f;
const float RATETWO = 0.0535f;
const float RATETHREE = 0.055f;
const float RATEFOUR = 0.0575f;
float billAmount;
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED);
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps);
void InstallmentPlan(float billAmount);
void BusinessEstimate(float PER_SQUARE_FOOT);
int main()
{
cout << fixed << showpoint << setprecision(2);
int customerType, residential_customer, business_customer;
char B, b, R, r;
residential_customer = R || r;
business_customer = B || b;
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; //Enter customer type
cout << endl;
while (cin) //While there is input to read
{
if (customerType == R || customerType == r) //if residential customer
{
ResidentialEstimate(SMALL_COUCH, LARGE_COUCH, ROOMS, STEPS, DISCOUNT_QUALIFIED); // call function ResidentialEstimate
InstallmentPlan(billAmount); // all function Installmentplan
}
else if (customerType == B || customerType == b) //else if business customer
{
BusinessEstimate(PER_SQUARE_FOOT); //call function BusinessEstimate
}
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; // Enter cutomer type
cout << endl;
}
return 0;
}
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED)
{
GetResidentialItems(smallcouches, largecouches, rooms, steps); //Call function GetResidentialItems to get items to clean
billAmount = (SMALL_COUCH + LARGE_COUCH + ROOMS + STEPS); //Calculate the bill amount
if (billAmount > 500) //if bill amount is more than 500 dollars
{
DISCOUNT_QUALIFIED = billAmount * 0.10f;
billAmount = billAmount - DISCOUNT_QUALIFIED; //Apply a discount of 10% to the bill amount
}
return billAmount; //return bill Amount
}
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps)
{
int count;
int choice = smallcouches || largecouches || rooms || steps;
//Ask user to select an item to update or press 0 to exit
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
while (choice > 0) //while user hasn't pressed 0
{
choice = count;
cout << "Please enter the number of " << choice; //ask the user to enter a number from the item selected
cin >> count;
cout << endl;
//Show the current selections and numbers
cout << "Current selections: " << count << " Small Couches, " << count << " Large Couches, " << count << " Rooms, " << count << " Steps.";
//Ask user to select an item to update or press 0 to exit
choice = 0;
count = 0;
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
}
}
void InstallmentPlan(float billAmount)
{
int num;
int installment = 0;
int bill = 0;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
while (num > 0) //while user hasn't pressed 0
{
//calculate the installments
if (num == 1)
installment = billAmount;
else if (num == 2)
{
bill = billAmount * 0.0535f;
installment = bill / num;
}
else if (num == 3)
{
bill = billAmount * 0.055f;
installment = bill / num;
}
else if (num == 4)
{
bill = billAmount * 0.0575f;
installment = bill / num;
}
cout << "With " << num << " installment your bill of " << billAmount << " will be worth " << bill << "." << endl;
cout << "Each installment will be worth " << installment << endl;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
}
}
void BusinessEstimate(float squarefootage)
{
//Ask user for the square footage
cout << " Enter the approximate square footage: ";
cin >> squarefootage;
cout << endl;
//Calculate the bill amount
billAmount = squarefootage * PER_SQUARE_FOOT;
cout << "Your free Business Customer Estimate for " << squarefootage << "square footage = " << billAmount;
}
I have this code here that works pretty decent except for when we get down to the 'processData' function where I receive the error
"The variable 'totalPay' is being used without being initialized."
I've been working on this for a couple hours and my brain is going numb, any help would be appreciated.
#include <iostream>
#include <string>
#include <climits>
#include <iomanip>
using namespace std;
// Prototypes
int readInt(string errorMsg = "", int min = INT_MIN, int max = INT_MAX);
void getData(string&, int&, char&, double&);
char getChoice(string prompt, char char1, char char2);
double processData(char service);
void display(string, int, char, double);
// Regular service
const double RCHARGE = 10.00; // Regular service base rate for first REG_MINS.
const double RPERMIN = 0.20; // Regular service cost per minute over REG_MINUTES.
const int REG_MINS = 50; // Regular service free minutes.
// Premium service
const double PCHARGE = 25.00; // Minimum charge for premium service.
const double P_PER_MIN_DAY = 0.10; // Charge per day minutes after 75.
const double P_PER_MIN_NIGHT = 0.05; // Charge per night minutes after 100.
const int P_DAY = 75; // Number of free minutes allowed during the day.
const int P_NIGHT = 100; // Number of free minutes allowed during the night.
int main()
{
string name; // Stores the users name.
int accountNumber; // Stores the users account number.
char serviceType; // Stores the users service type.
double minutes; // Stores the users minutes.
double totalPay; // Recieves the total pay from processData.
bool loopies = true;// Controls the loop while condition is true.
while (loopies == true)
{
getData(name, accountNumber, serviceType, minutes);
totalPay = processData(serviceType);
display(name, accountNumber, serviceType, totalPay);
}
return 0;
}
// Checks ints to make sure they are valid.
int readInt(string errorMsg, int min, int max)
{
int someInt;
bool valid = false;
do
{
// User entering account number
cin >> someInt;
// Verifying the data is valid (0 to 9999)
valid = (someInt >= min && someInt <= max);
// Clearing out invalid data and prompting for re-entry
if (cin.fail() || !valid || !isspace(cin.peek()))
{
cout << "Error! Invalid input." << endl;
cout << errorMsg << " must be whole number between " << min << " and " << max << endl;
cout << "Try Again: ";
cin.clear(); // Clearing the fail state
cin.ignore(numeric_limits<streamsize>::max(), '\n');
valid = false;
}
} while (!valid);
// Clears out following incorrect data once correct
cin.ignore(100, '\n');
return someInt;
}
// Takes all user data and checks input.
void getData(string &name, int &account, char &service, double &bill)
{
cout << "Enter customer name or \"Exit\" to end program: ";
getline(cin, name);
if (name == "Exit" || name == "EXIT" || name == "exit")
{
cout << "Program closing..." << endl;
system("pause");
exit(EXIT_SUCCESS);
}
cout << "Enter account number: ";
account = readInt("Account", 0, 10000);
cout << "Enter service type (R for regular or P for premium): ";
service = getChoice("Service", 'r', 'p' );
}
char getChoice(string input, char char1, char char2)
{
char character; // Stores the users character.
bool valid = false; // Controls the loop.
do
{
cin >> character;
character = tolower(character);
valid = (character == char1 || character == char2);
if (!valid || !isspace(cin.peek())) {
cout << "Invalid input!" << endl;
cout << input << " needs to be " << char1 << " or " << char2 << endl;
cout << "Try again: ";
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
valid = false;
}
} while (!valid);
cin.ignore(100, '\n');
return toupper(character);
}
double processData(char service)
{
int dayMin; // Stores the users day minutes.
int nightMin; // Stores the users night minutes.
double totalPay; // Stores the total pay.
double dayPay; // Stores the pay for day minutes.
double nightPay; // Stores the pay for night minutes.
if (service == 'r')
{
cout << "Enter minutes used: ";
cin >> dayMin;
dayMin = readInt("Minutes ", 0, INT_MAX);
if (dayMin > REG_MINS)
{
dayMin -= REG_MINS;
totalPay = (dayMin * RPERMIN) + RCHARGE;
}
else
{
totalPay = RCHARGE;
}
totalPay = nightPay + dayPay - RCHARGE;
}
else if (service == 'p')
{
cout << "Enter day minutes: ";
cin >> dayMin;
dayMin = readInt("Minutes ", 0, INT_MAX);
if (dayMin > P_DAY)
{
dayMin -= P_DAY;
dayPay = (dayMin * P_PER_MIN_DAY) + PCHARGE;
}
else
{
dayPay = PCHARGE;
}
cout << "Enter night minutes: ";
cin >> nightMin;
nightMin = readInt("Minutes ", 0, INT_MAX);
if (nightMin > P_NIGHT)
{
nightMin -= P_NIGHT;
nightPay = (nightMin * P_PER_MIN_NIGHT) + PCHARGE;
}
else
{
nightPay = PCHARGE;
}
}
return totalPay;
}
void display(string name, int account, char service, double bill)
{
string switchService;
switch (service)
{
case 'R':
switchService = "Regular";
break;
case 'P':
switchService = "Premium";
break;
default:
cout << "Invalid character.";
}
cout << fixed << setprecision(2);
cout << endl;
cout << "Customer Name: " << name << endl;
cout << "Account number: " << account << endl;
cout << "Service type: " << switchService << endl;
cout << "Amount due: $" << bill << endl << endl;
}
In processData(), if service is neither p nor r, totalPay is never assigned before returning.
You may initialize it on declaration like
double totalPay = 0.0;
So I need to create a function that will turn the COUT part ONLY of each "if" statement:
// Respond to the user's menu selection
if (choice == ADULT_CHOICE)
{
charges = months * ADULT;
cout << over3 << "The total charges are $" << charges << endl;
}
else if (choice == CHILD_CHOICE)
{
charges = months * CHILD;
cout << over3 << "The total charges are $" << charges << endl;
}
else if (choice == SENIOR_CHOICE)
{
charges = months * SENIOR;
cout << over3 << "The total charges are $" << charges << endl;
}
Into a summary function that reads like THIS.
So far I have made a total mess of the code and I really need some help... here is what I have so far but most of it is probably not salvageable:
function prototype:
int summary(string, int, int, double);
Main:
//variables
int choice; // menu choice
int months; //number of months
double charges; //monthly charges
string type1 = "Adult", type2 = "Child", type3 = "Senior";
if (choice == ADULT_CHOICE)
{
charges = months * ADULT;
cout << summary(type1, months, 40, charges);
}
else if (choice == CHILD_CHOICE)
{
charges = months * CHILD;
cout << summary(type2, months, 20, charges);
}
else if (choice == SENIOR_CHOICE)
{
charges = months * SENIOR;
cout << summary(type3, months, 30, charges);
}
function definition:
int summary(string type, int months, int price , double charges)
{
system("CLS");
cout << down7;
cout << over3 << " Summary of Charges \n"
<< over3 << "----------------------------\n"
<< over3 << "Membership Type: " << type << endl;
cout << over3 << "Number of Months: " << months << endl;
cout << over3 << "Membership Prices: " << price << endl;
cout << over3 << "Total of Charges: " << charges << endl;
}
I know there is a lot wrong here and I just needed some help going in the right direction. I have no idea how to solve the string variable stuff, should I keep going that route? or go an other way entirely?
Thanks for any help!
There are several designs and implementations for your requirements.
switch statement
Instead of all these if-else-if in a ladder, use a switch statement. I believe a switch statement would be more readable:
double rate = 0.0;
std::string type_name;
double price = 0.0;
switch (choice)
{
case ADULT_CHOICE:
rate = adult_rate;
type_name = "Adult";
price = 40;
break;
case CHILD_CHOICE:
rate = child_rate;
type_name = "Child";
price = 20;
break;
case SENIOR_CHOICE:
rate = senior_rate;
type_name = "Senior";
price = 30;
break;
default:
cerr << "Invalid ticket type\r\n";
exit(1);
}
charges = months * rate;
summary(type_name, months, price, charges);
Look up table
A more maintainable design and implementation is to use a look up table. Create a table of entries that contain information about a ticket. (This will lead up to the last design consideration).
struct Ticket
{
unsigned int choice;
char const * type_name;
double price;
double rate;
};
const Ticket ticket_info[] =
{
{ADULT_CHOICE, "Adult", 40, ADULT_RATE},
{CHILD_CHOICE, "Child", 10, CHILD_RATE},
{SENIOR_CHOICE, "Senior", 30, SENIOR_RATE},
};
const unsigned int maximum_ticket_types =
sizeof(ticket_info) / sizeof(ticket_info[0]);
for (unsigned int i = 0; i < maximum_ticket_types; ++i)
{
if (choice == ticket_info[i].choice)
{
summary(ticket_info[i].type_name,
months,
ticket_info[i].price,
ticket_info[i].rate * months);
break;
}
}
This has the advantage that you can test it with only 1 entry and then add additional entries without adding additional code.
Object Oriented
In the Object Oriented approach, you would have either a ticket object (like the structure above) or have Parent Ticket and child ticket objects. The objects would contain methods for printing a summary.
Here is a sample:
class Ticket_Base
{
public:
friend std::ostream& operator>>(std::ostream& output, const Ticket_Base& ticket);
double rate;
double price;
std::string type_name;
};
class Adult_Ticket : public Ticket_Base
{
public:
Adult_Ticket()
: rate(ADULT_RATE), price(40), type_name("Adult");
};
The senior and child ticket classes would look the same as the adult ticket.
You could use the Factory Pattern to create tickets and a generic function to print the ticket summary.
I have to display and loop a menu, allowing the customer to make multiple orders for peanuts, movies, or books. The menu displays fine, but the quantity doesn't go down to the calculations part of my code. Everytime I enter a quantity for anything and checkout it returns $0. I have no idea why this is happening I don't see anything wrong with my code, but obviously there is. Do you guys have any suggestions on what to do based on looking at what I have?
#include <iostream>
#include <cstdlib>
using namespace std;
//function declarations
void displayMenu();
//constant statements
const double BOOK_PRICE = 9.00; //price per book
const double BOOK_SHIPPING = 1.06; //shipping per book
const double MOVIE_PRICE = 13.99; //price per movie
const double MOVIE_SHIPPING = .05; //shipping per movie subtotal
const double PEANUT_PRICE = 1.80; //price of peanuts per pound
const double SHIPPING_PRICE = .50; //shipping of peanuts per lb
int main()
{
//declaration statements
int numBooks = 0; //# of books purchased
int numMovies = 0; //# of movies purchased
double numPeanuts = 0.0; //# of peanuts per pound
double bookSubtotal = 0.0; //subtotal of books
double movieSubtotal = 0.0; //subtotal of movies
double peanutSubtotal = 0.0; //subtotal of peanuts
int totalBooks = 0; //running total of books
int totalMovies = 0; //running total of movies
double totalPeanuts = 0.0; //running total of peanuts
int userChoice = 0; //user input
double totalPrice = 0.0; //final price
while (userChoice != 4)
{
displayMenu();
cout << "Enter a menu choice: ";
cin >> userChoice;
if (userChoice == 1)
{
cout << "Please enter the number of books: ";
cin >> numBooks;
totalBooks = totalBooks + numBooks;
}
else if (userChoice == 2)
{
cout << "Please enter the number of movies: ";
cin >> numMovies;
totalMovies = totalMovies + numMovies;
}
else if (userChoice == 3)
{
cout << "Please enter the pounds of peanuts as a decimal: ";
cin >> numPeanuts;
totalPeanuts = totalPeanuts + numPeanuts;
}
else if (userChoice == 4)
{
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
//computations
bookSubtotal = (totalBooks * BOOK_PRICE) + (totalBooks * BOOK_SHIPPING);
movieSubtotal = (totalMovies * MOVIE_PRICE * .05) + (totalMovies * MOVIE_PRICE);
peanutSubtotal = (PEANUT_PRICE * totalPeanuts) + (totalPeanuts * .5);
totalPrice = bookSubtotal + movieSubtotal + peanutSubtotal;
cout << "The total price is $" << totalPrice << endl;
system("PAUSE");
return 0;
}//end of main
void displayMenu()
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Peanuts" << endl;
cout << "4 Checkout" << endl;
}//end of displayMenu
The problem is in the cin >> - you found the answer yourself when you say that the book count is zero. I suggest you try to put << endl after each cout << .... Other solution is to use _flushall(); after each cout.