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;
Related
I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}
The program is supposed to repeat after the user enters incorrect data for hours, minutes, seconds.
I can't get programs to loop on Xcode.
Example:
user enters invalid data for hours, minutes, and seconds.
Program displays "invalid data", and then asks the user if they would like to repeat the program, if the user enters "y or Y", the program asks the user to enter the time again.
#include <iostream>
#include <iomanip>
using namespace std;
struct Time
{
int hours ;
int seconds;
int minutes;
};
void getTime(Time &time);
bool isTimeValid(Time &time);
void addOneSecond(Time &time);
void displayTime(Time &time);
const int MAX_HOURS = 23;
const int MAX_MINS = 59;
const int MAX_SECS = 59;
int main()
{
Time time;
getTime(time);
isTimeValid(time);
addOneSecond(time);
displayTime(time);
return 0;
}
void getTime(Time &time)
{
cout << "Enter the time in \"military time\", (24-hour format), in"
<< " the following order:\nHH:MM:SS, (Hours, Minutes, Seconds).\n\n";
cout << "Hours: ";
cin >> time.hours;
cout << "Minutes: ";
cin >> time.minutes;
cout << "Seconds: ";
cin >> time.seconds;
cout << endl << endl;
}
bool isTimeValid(Time &time)
{
bool answer = ' ';
if (((time.hours >= 0) && (time.hours <= MAX_HOURS)) &&
((time.minutes >= 0) && (time.minutes <= MAX_MINS)) &&
((time.seconds >= 0) && (time.seconds <= MAX_SECS)))
{
return true;
}
else
{
cout << "Invalid Time.\n\n";
return false;
}
cout << "Do it again? (Y/N)";
cin >> answer;
do
{
getTime(time);
isTimeValid(time);
addOneSecond(time);
displayTime(time);
} while(toupper(answer) == 'T' );
}
void addOneSecond(Time &time)
{
time.seconds++;
if (time.seconds > MAX_SECS)
{
time.seconds = 0;
time.minutes++;
}
}
void displayTime(Time &time)
{
cout.fill('0');
cout << "After adding one second, the time is " << setw(2) << time.hours
<< ":" << setw(2) << time.minutes << ":" << setw(2)
<< time.seconds << ".\n\n";
}
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;
}
}
I don't understand why my code is not calculating the birthrate and the deathrate. I keep on getting 0 for both. I included the static_cast<double> to ensure this wouldn't happen. Any feedback / help?
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
int getBirths()
{
return birthrate;
}
int getDeaths()
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
void calculateBirthRate(PopInfo);
void calculateDeathRate(PopInfo);
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
void PopInfo::calculateBirthRate(PopInfo newCity)
{
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
You accidentally made birthrate and deathrate as local variables. Remove the leading keyword double, to make it:
void PopInfo::calculateBirthRate(PopInfo newCity)
{
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
Even so, it's kind of strange that you're passing newCity by value – did you mean to store the rates back in the same object, as in:
void PopInfo::calculateBirthRate(PopInfo& newCity)
{
newCity.birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo& newCity)
{
newCity.deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
or did you mean to operate on the object in-place, as in:
void PopInfo::calculateBirthRate()
{
birthrate = static_cast<double>(bir) / citpop;
}
void PopInfo::calculateDeathRate()
{
deathrate = static_cast<double>(dea) / citpop;
}
I don't think you ever call the functions that calculate birth rate and death rate! That is on top of the issues already identified, but I'm pretty sure it matters... Put a cout debug statement in there and see if I'm right...
Another problem: since "rate" is a number between zero and 1, and your function getBirths returns an int, you are going to run into a rounding problem...
Also not sure you ever set dea and bir in the context of the class (you declare them at the main level). So many places where you are inviting problems...
The easiest solution would be to rewrite these two functions:
double getBirths()
{
return (double)numberOfBirths/citypop;
}
double getDeaths()
{
return (double)numberOfDeaths/citypop;
}
But read your code, and ask yourself what the scope of your variables is, where they are set (and if you ever set them...), where they are used, where you perform type conversions.... You can learn a lot from that.
EDIT
I couldn't help myself, and decided to copy your program and debug it. After a few simplifications in the structure I came up with the following (note I moved the two functions calculateBirthRate and calculateDeathRate inside the class definition for consistency; and I used the "internally known" variables totalCityPopulation etc, rather than some of the "alternative" ones you were using... it was getting very confusing. Finally, as I mentioned in the original answer - I made sure the birth and death rates were actually calculated. I have marked changed lines with //*** :
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
double getBirths() //*** was int
{
return birthrate;
}
double getDeaths() //*** was int
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
//*** this function moved into the class definition
void calculateBirthRate()
{
birthrate = (double)numberOfBirths/totalCityPopulation; //*** using different variables
}
//*** this function moved into the class definition
void calculateDeathRate()
{
deathrate = (double)numberOfDeaths / totalCityPopulation; //*** using different variables
}
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
newCity.calculateBirthRate(); //*** added, or it's never calculated
newCity.calculateDeathRate(); //*** added, or it's never calculated
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
When I run this code, I get the following:
What is the city name?:
Amsterdam
What is the total city population?:
1234567
What are the number of births?:
12345
What are the number of deaths?:
54321
The city name is Amsterdam
The total city population is 1234567
The birth rate is 0.00999946
The death rate is 0.044
The diff between your code and mine is:
33c33
< double getBirths()
---
> int getBirths()
38c38
< double getDeaths()
---
> int getDeaths()
68,71c68,69
< void calculateBirthRate()
< {
< birthrate = (double)numberOfBirths/totalCityPopulation;
< }
---
> void calculateBirthRate(PopInfo);
> void calculateDeathRate(PopInfo);
73,76d70
< void calculateDeathRate()
< {
< deathrate = (double)numberOfDeaths / totalCityPopulation;
< }
117,118d110
< newCity.calculateBirthRate();
< newCity.calculateDeathRate();
129a122,125
> void PopInfo::calculateBirthRate(PopInfo newCity)
> {
> double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
> }
130a127,130
> void PopInfo::calculateDeathRate(PopInfo newCity)
> {
> double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
> }
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
Here you are driving two new variable names birthrate and death rate. You're not writing the values two the class data members. Writing the type before the names overwrites it. To change, simply remove it.
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
\a3.cpp(75): error C2563: mismatch in formal parameter list
I'm certain I'm passing the function checkout with 3 doubles, I don't know why I'm getting the error I am. Please help.
#include <iostream>
#include <cstdlib>
using namespace std;
const double peanut_PRICE = 1.80;
const double peanut_SHIP = 0.50;
const double BOOK_PRICE = 9;
const double BOOK_SHIP = 1.06;
const double MOVIE_PRICE = 13.99;
const double MOVIE_SHIP = 0.05;
double checkout (double myamountofbooks, double myamountofmovies, double mypoundsofpeanuts)
{
myamountofbooks = myamountofbooks * (BOOK_PRICE + BOOK_SHIP);
myamountofmovies = myamountofmovies * MOVIE_PRICE * (1 + MOVIE_SHIP);
mypoundsofpeanuts = mypoundsofpeanuts * (peanut_PRICE + peanut_SHIP);
return (myamountofbooks + myamountofmovies + mypoundsofpeanuts);
}
bool validUserImput (int whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
bool validUserImput (double whereUserWantsToGoNext)
{
if (whereUserWantsToGoNext > 50 || whereUserWantsToGoNext < 0)
return false;
else return true;
}
int main()
{
//===========================Declaration Statements==================================
double amountofbooks = 0;
double amountofmovies = 0;
double poundsofpeanuts = 0;
int whereUserWantsToGoNext = 0;
while (! (whereUserWantsToGoNext == 4) )
{
cout << "1. Books\n2. Peanuts\n3. Movies\n4. Checkout\n" << endl;
cin >> whereUserWantsToGoNext;
if (!validUserImput(whereUserWantsToGoNext)) cout << "INVALID IMPUT" << endl;
if (whereUserWantsToGoNext == 1){
cout << "Please enter your number of books";
cin >> amountofbooks;
if (!validUserImput(amountofbooks)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 3){
cout << "Now please enter the number of movies you've selected";
cin >> amountofmovies;
if (!validUserImput(amountofmovies)) cout << "INVALID IMPUT" << endl;
}
if (whereUserWantsToGoNext == 2) {
cout << "Please enter the weight(in pounds) of your peanuts";
cin >> poundsofpeanuts;
if (!validUserImput(poundsofpeanuts)) cout << "INVALID IMPUT" << endl;
}
if (validUserImput == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
}
cin >> amountofbooks;
}
The problem is here:
if (validUserImput == 4) ...
validUserImput is a function, but you are not calling that function, you are trying to compare it to 4.
If you wanted to keep track of the number of valid inputs you received, you could instead add a new variable that you manually increment on every valid input.
The last if - you are comparing function pointer to an integer. try this:
if (validUserImput(3) == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts);
I assume you want to display the result of the checkout function if the user selects 4. So you probably wanted to write:
if (whereUserWantsToGoNext == 4) cout << "Total Cost is..." << checkout(amountofbooks, amountofmovies, poundsofpeanuts) << endl;