C++ Problems inputting value into class objects - c++

I am taking a class on C++ currently and need help with a certain part of my code. It all compiles but when I go to test it I am only allowed to input one value into the window before the rest of the code advances through without input.
For reference, this is the question I am answering:
11. Payroll
Design a PayRoll class that has data members for an employee’s hourly pay rate, number of hours worked of type double . The default constructor will set the hours worked and pay rate to zero. The class must have a mutator function to set the pay rate for each employee and hours worked. The class should include accessors for both the hours worked and the rate of pay. The class should lastly have a getGross function that will return a double calculated by multiplying the hours worked by the rate
of pay.
Write a program with an array of seven PayRoll objects . The program should ask the user for the rate of pay for each employee and the number of hours each employee has worked. Be sure to include an employee claiming to work more then 60 hours per week. Print out, the array number of the employee, the hours worked, the rate of pay, and the gross pay, of all the employee's each on their own line. Set the precision for printing the doubles to two decimal places.
Input Validation: Do not accept values greater than 60 for the number of hours worked, simply have the set function set number of hours worked to 60, the maximum allowed.
My code is as follows:
#include <iostream>
#include <iomanip>
//Garrett Bartholomay
/*This program defines and implements the Payroll class.
* The class is then used in a program that calculates gross pay for an array of
* Payroll objects after accepting values for hours and pay rate from standard input*/
class Payroll
{
private:
int hoursWorked;
double payRate;
public:
Payroll();
Payroll(int, double);
void setHours(int);
void setPayRate(double);
int getHours() const;
double getPayRate() const;
double getGross()const;
};
Payroll::Payroll()
{
hoursWorked = 0;
payRate = 0.0;
}
Payroll::Payroll(int h, double r)
{
payRate = r;
hoursWorked = h;
}
void Payroll::setHours(int h)
{
hoursWorked = h;
}
void Payroll::setPayRate(double p)
{
payRate = p;
}
int Payroll::getHours() const
{
return hoursWorked;
}
double Payroll::getPayRate() const
{
return payRate;
}
double Payroll::getGross() const
{
double gross = static_cast<double>(hoursWorked) * payRate;
return gross;
}
using namespace std;
int main()
{
const int NUM_EMPLOYEES = 7;
Payroll employee[NUM_EMPLOYEES];
int pay;
int hours;
int i;
double grossPay;
for (i = 0; i < NUM_EMPLOYEES; i++)
{
cout << "Enter the # " << (i) << " employee's rate of pay per hour: ";
cin >> pay;
cout << "Enter the # " << (i) << " employee's hours worked for the week: ";
cin >> hours;
employee[i].setPayRate(pay);
employee[i].setHours(hours);
}
cout << "\n\nHere is the gross pay for each employee:\n";
cout << fixed << showpoint << setprecision(2);
for (int i = 0; i < NUM_EMPLOYEES; i++)
{
grossPay = employee[i].getGross();
cout << "The gross pay for employee # " << (i) << " is: " << grossPay << endl;
}
return 0;
}
The input resides within the loops.
Any help would be greatly appreciated.
Thanks,
G

Related

Math logic incorrect in function?

I am working on this exercise and it is pretty much complete but the math has to be wrong somewhere when calculating the senior citizen discount. The software that I use runs these two pieces of input to check the problem.
20
10
n
2
12 (which runs fine)
20
10
y
2
12 (does not not give me expected result)
This leads me to believe that the problem lies within the senior citizen discount part in the double determineMembershipCost function.
The expected result is "The membership cost = $162.80" but my code gives me "The membership cost = $152.00"
I am not sure what is wrong here. I'm hoping a second set of eyes can help find it. Thank you in advance.
Here is the code:
// headers
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// prototypes
void displayGeneralInformation ();
void readNecessaryInformation (double& regularCostPerMonth,
double& costPerPersonalTrainingSession,
bool& seniorCitizen, int& numberOfSessions,
int& numberOfMonths);
double determineMembershipCost (double regularCostPerMonth,
double costPerPersonalTrainingSession,
bool seniorCitizen, int numberOfSessions,
int numberOfMonths);
// main
int main()
{
//variables
double regularCostPerMonth;
double costPerPersonalTrainingSession;
bool seniorCitizen;
int numberOfSessions;
int numberOfMonths;
double cost;
// print menu
// calls
// call displayGeneralInformation
displayGeneralInformation ();
// call readNecessaryInformation
readNecessaryInformation (regularCostPerMonth,
costPerPersonalTrainingSession,
seniorCitizen, numberOfSessions,
numberOfMonths);
// call determineMembershipCost
cost = determineMembershipCost (regularCostPerMonth, costPerPersonalTrainingSession, seniorCitizen, numberOfSessions, numberOfMonths);
// Display cost of membership
cout << "\nThe membership cost = $" << setprecision(2)<< fixed << cost << endl;
return 0;
}
// displayGeneralInformation function definition
void displayGeneralInformation ()
{
cout << "\nWelcome to Stay Healthy 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% off 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;
}
// readNecessaryInformation function definition
void readNecessaryInformation (double& regularCostPerMonth,
double& costPerPersonalTrainingSession,
bool& seniorCitizen, int& numberOfSessions,
int& numberOfMonths)
{
cout << "\nEnter the cost of a regular membership per month: $";
cin >> regularCostPerMonth;
cout << "Enter the cost of one personal training session: $";
cin >> costPerPersonalTrainingSession;
cout << "Are you a senior citizen (Y,y/N,n): ";
char ch;
cin >> ch;
if (ch == 'Y' || ch == 'y')
seniorCitizen = true;
else
seniorCitizen = false;
cout << "Enter the number of personal training sessions bought: ";
cin >> numberOfSessions;
cout << "Enter the number of months you are paying for: ";
cin >> numberOfMonths;
}
// determineMembershipCost function definition
double determineMembershipCost (double regularCostPerMonth, double costPerPersonalTrainingSession, bool seniorCitizen, int numberOfSessions, int numberOfMonths)
{
double cost = regularCostPerMonth * numberOfMonths;
if (seniorCitizen)
{
cost = cost - (regularCostPerMonth * 0.30 * numberOfMonths);
}
if (numberOfMonths >= 12)
{
cost = cost - (regularCostPerMonth * 0.15 * numberOfMonths);
}
cost = cost + (costPerPersonalTrainingSession * numberOfSessions);
if (numberOfSessions > 5)
{
cost = cost - (costPerPersonalTrainingSession * 0.20 * numberOfSessions);
}
return cost;
}
Try this instead:
cost = (cost - (cost * 0.30)); //for 30% off
cost = (cost - (cost * 0.15)); //15% off

initialize class functions but output still 0

I am having problems with this program. When I compile it, I intialize all of the variables based upon the users input, but the cout still shows that the problem has '0' for most of the statements and for one of the statements its a '-negative' number. Any thoughts?
#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
float term;
public:
void setData(float, float, float);
float setTerm ();
float monthly;
float total;
float interest;
int years;
float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
loan = l;
interest = i;
years = y;
setTerm();
}
float MortgageCalc::setTerm()
{ //simple interest calculation with power calc to establish whole number translation
term = pow((1 + ((interest/100) / 12)), (12 * years));
return term;
}
class mPayment : public MortgageCalc
{
public:
int monthly()
{
return ((loan * ((interest/100) / 12) * term ) / (term - 1));
}
};
class tPayment : public mPayment
{
public:
int total()
{
return (monthly() * (years * 12));
}
};
class iPayment : public tPayment
{
public:
int plusInterest()
{
return (total() - loan);
}
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
cin >> loan;
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest;
cout << "Enter the length of the loan in years: "; //establishes term of payments
cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};
You are taking all different objects like MortgageCalc mort1; mPayment m; tPayment t; iPayment i;.
These object do not have any relation.
Example:
mort1 = {term, monthly, total, interest, years, loan}
and suppose you have initialize with 1
mort1 = {term=1, monthly=1, total=1, interest=1, years=1, loan=1}
but it doesnot impact to the m because both are stored in memory on different location.
m = {term=0, monthly=0, total=0, interest=0, years=0, loan=0}
You can check both have different base address like cout<<&mort1<<endl<<&m; .
Data member you have set is part of MortgageCalc mort1 instead of mPayment m; tPayment t;.
You need to brush up your C++ basic's.
You use default constructors on those lines:
mPayment m;
tPayment t;
iPayment i;
They have no notion of previously input data held in mort1. You did not take care for any way to "share" or "communicate" this data.
m,t,i were all initialized with random data. There is no relation to mort1.
I won't go into details of what correct architecture here would be, but you should read about base class initialization. As a hint I'd say in your (a little weird) example you could try making this syntax work:
mPayment m(mort1);

Can't get rid of Error lnk2001 [duplicate]

This question already has answers here:
Can't set value of static object field (error LNK2001: unresolved external symbol)
(2 answers)
Closed 7 years ago.
Hey guys and gals I need some serious assistance. I have this final and its due in 2 days and some hours. However I am unable to resolve this lnk2001 error at the end of my program. Please help me I have no clue how to resolve. I left the instructors desires in the coding as comments.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
using std::cout;
using std::cin;
using std::endl;
//
//CLASS DECLARATION SECTION
//
class EmployeeClass {
public:
void ImplementCalculations(string EmployeeName, double hours, double wage);
void DisplayEmployInformation(void);
static double Addsomethingup(EmployeeClass, EmployeeClass, EmployeeClass);
string EmployeeName;
double hours;
double wage;
double basepay;
double overtime_hours;
double overtime_pay;
double overtime_extra;
static double iTotal_salaries;
static double iIndividualSalary;
static double iTotal_hours;
static double iTotal_OvertimeHours;
};
int main()
{
system("cls");
cout << "Welcome to the Employee Pay Center" << endl;
/*
These are my three employees
*/
EmployeeClass Employ1;
EmployeeClass Employ2;
EmployeeClass Employ3;
/*
Here you will prompt for the first employee’s information.
Prompt the employee name, hours worked, and the hourly wage. For each piece
of information, you will update the appropriate class member defined above.
Example of Prompts
Enter the employee name =
Enter the hours worked =
Enter his or her hourly wage =
*/
cout << "Enter the employee name." << endl;
cin >> Employ1.EmployeeName;
cout << "Enter the hours worked." << endl;
cin >> Employ1.hours;
cout << "Enter his or her hourly wage." << endl;
cin >> Employ1.wage;
/*
Here you will prompt for the second employee’s information.
Prompt the employee name, hours worked, and the hourly wage. For each piece
of information, you will update the appropriate class member defined above.
Enter the employee name =
Enter the hours worked =
Enter his or her hourly wage =
*/
cout << "Enter the employee name." << endl;
cin >> Employ2.EmployeeName;
cout << "Enter the hours worked." << endl;
cin >> Employ2.hours;
cout << "Enter his or her hourly wage." << endl;
cin >> Employ2.wage;
/*
Here you will prompt for the third employee’s information.
Prompt the employee name, hours worked, and the hourly wage. For each piece
of information, you will update the appropriate class member defined above.
Enter the employee name =
Enter the hours worked =
Enter his or her hourly wage =
*/
cout << "Enter the employee name." << endl;
cin >> Employ3.EmployeeName;
cout << "Enter the hours worked." << endl;
cin >> Employ3.hours;
cout << "Enter his or her hourly wage." << endl;
cin >> Employ3.wage;
/*
Here you will implement a function call to implement the employ calcuations
for each object defined above. You will do this for each of the three
employees or objects.
The format for this step is the following:
[(object name.function name(objectname.name, objectname.hours,
objectname.wage)] ;
*/
Employ1.ImplementCalculations(Employ1.EmployeeName, Employ1.hours,
Employ1.wage);
Employ2.ImplementCalculations(Employ2.EmployeeName, Employ2.hours,
Employ2.wage);
Employ3.ImplementCalculations(Employ3.EmployeeName, Employ3.hours,
Employ3.wage);
EmployeeClass::Addsomethingup(Employ1, Employ2, Employ3);
}
/*
This section you will send all three objects to a function that will add up
the the following information:
- Total Employee Salaries
- Total Employee Hours
- Total Overtime Hours
The format for this function is the following:
- Define a new object.
- Implement function call [objectname.functionname(object name 1, object
name 2, object name 3)]
/*
} //End of Main Function*/
void EmployeeClass::ImplementCalculations (string EmployeeName, double
hours, double wage){
//Initialize overtime variables
basepay = wage;
overtime_hours=0.0;
overtime_pay=0.0;
overtime_extra=0.0;
if (hours > 40)
{
EmployeeClass::hours = 40.0;
EmployeeClass::overtime_hours = hours - 40;
EmployeeClass::overtime_pay = wage * 1.5;
EmployeeClass::overtime_extra = overtime_hours * overtime_pay;
EmployeeClass::iIndividualSalary = overtime_extra + (wage *
EmployeeClass::hours);
/*
This section is for the basic calculations for calculating overtime pay.
- base pay = 40 hours times the hourly wage
- overtime hours = hours worked – 40
- overtime pay = hourly wage * 1.5
- overtime extra pay over 40 = overtime hours * overtime pay
- salary = overtime money over 40 hours + your base pay
*/
/*
Implement function call to output the employee information. Function is
defined below.
*/
}
else
{
EmployeeClass::hours = hours;
EmployeeClass::overtime_hours = 0.0;
EmployeeClass::overtime_pay = 0.0;
EmployeeClass::overtime_extra = 0.0;
EmployeeClass::iIndividualSalary = wage * EmployeeClass::hours;
/* Here you are going to calculate the hours less than 40 hours.
- Your base pay is = your hours worked times your wage
- Salary = your base pay
*/
/*
Implement function call to output the employee information. Function is
defined below.
*/
} // End of the else
DisplayEmployInformation();
} //End of Primary Function
void EmployeeClass::DisplayEmployInformation(void)
{
// This function displays all the employee output information.
//This is your cout statements to display the employee information:
cout << "Employee Name ............. =" << EmployeeName << endl;
cout << "Base Pay .................. =" << basepay << endl;
cout << "Hours in Overtime ......... =" << overtime_hours << endl;
cout << "Overtime Pay Amount........ =" << overtime_pay << endl;
cout << "Total Pay ................. =" << iIndividualSalary << endl;
} // END OF Display Employee Information
double EmployeeClass::Addsomethingup(EmployeeClass Employ1, EmployeeClass
Employ2, EmployeeClass Employ3)
{
Employ1.DisplayEmployInformation();
// Adds two objects of class Employee passed as
// function arguments and saves them as the calling object's data member
values.
EmployeeClass::iTotal_hours = Employ1.hours + Employ2.hours + Employ3.hours;
double myhours;
EmployeeClass::iTotal_hours = Employ1.hours + Employ2.hours + Employ3.hours;
myhours = Employ1.hours + Employ2.hours + Employ3.hours;
EmployeeClass::iTotal_OvertimeHours = Employ1.overtime_hours +
Employ2.overtime_hours + Employ3.overtime_hours;
EmployeeClass::iTotal_salaries = Employ1.iIndividualSalary +
Employ2.iIndividualSalary + Employ3.iIndividualSalary;
/*
Add the total hours for objects 1, 2, and 3.
Add the salaries for each object.
Add the total overtime hours.
*/
// Then display the information below.
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% " << endl;
cout << "%%%% EMPLOYEE SUMMARY DATA%%%%%%%%%%%%%%%%%%%%%%% " << endl;
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% " << endl;
cout << "%%%% Total Employee Salaries ..... = " << iTotal_salaries << endl;
cout << "%%%% Total Employee Hours ........ = " << iTotal_hours << endl;
cout << "%%%% Total Overtime Hours......... = " << iTotal_OvertimeHours <<
endl;
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% " << endl;
cout << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% " << endl;
return 0;
} // End of function
Non-integral static member variables must be defined outside the class definition.
class EmployeeClass
{
// ...
static double iTotal_salaries;
static double iIndividualSalary;
static double iTotal_hours;
static double iTotal_OvertimeHours;
};
double EmployeeClass::iTotal_salaries = 0.0;
double EmployeeClass::iIndividualSalary = 0.0;
double EmployeeClass::iTotal_hours = 0.0;
double EmployeeClass::iTotal_OvertimeHours = 0.0;

User input giving wrong results

Okay well, I am having trouble with the user input from taxRate, when I compile the code I get the wrong results.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
long propertyValue;
long taxRate;
long exemption = 5000;
cout << "What is the actual value of your property?\n";
cin >> propertyValue;
cout << "What is the current tax rate?\n";
cin >> taxRate;
cout << "You will pay an annual property tax of ";
cout << (propertyValue - exemption) * taxRate / 100.00;
cout << " on your property\n";
cout << "and your quarterly tax bill will be; ";
cout << (propertyValue - exemption) * taxRate / 100.00 / 4 << endl;
system("pause");
return 0;
}
This is a simple error in the code, I'll explain why.
Let's take for example a PropertyValue of 300,000 and a tax rate of let's say 5.6.
You used the formula for the annual property tax rate:
(PropertyValue - exemption) * taxRate / 100.00;
And you declared taxRate as a long (aka a long int)
long taxRate;
300,000 - 5000 = 295,000 * 5.6 <----- Your mistake is right here!
Remember, long is a property of int so 5.6 becomes 5. Changing it to a double (floating-point number) will fix your problem. I tested this several times and it fix's your code.

I need help with classes. (C++)

Well I am trying to do an exercise in my programming book and it's difficult for me to grasp exactly what it wants.
My "enterAccountData()" function is suppose to ask the user for an account number and a balance neither of which can be negative and the account number cannot be less than 1000
The second one is the one I am stuck on "computeInterest()" THis function is suppose to accept an integer argument that represents the number of years the account will earn interest. The function then displays the account number from the previous function and displays its ending balance at the end of each year based on the interest rate attached to the BankAccount class. (The interest rate on "BankAccount" has to be a constant static field which is set at 3 percent(0.03)).
So My question is this: How do I set up "computeInterest()" too allow it to calculate the interest using the constant static field when my debugger will not allow me to actually keep the field as a constant? I am not trying to stop any random errors from happening for now, just trying to get the jist of what the book is exactly asking for. Here is my code.
#include <iostream>
#include <iomanip>
using namespace std;
class BankAccount
{
private:
int accountNum;
double accountBal;
static double annualIntRate;
public:
void enterAccountData(int, double);
void computeInterest();
void displayAccount();
};
//implementation section:
double BankAccount::annualIntRate = 0.03;
void BankAccount::enterAccountData(int number, double balance)
{
cout << setprecision(2) << fixed;
accountNum = number;
accountBal = balance;
cout << "Enter the account number " << endl;
cin >> number;
while(number < 0 || number < 999)
{
cout << "Account numbers cannot be negative or less than 1000 " <<
"Enter a new account number: " << endl;
cin >> number;
}
cout << "Enter the account balance " << endl;
cin >> balance;
while(balance < 0)
{
cout << "Account balances cannot be negative. " <<
"Enter a new account balance: " << endl;
cin >> balance;
}
return;
}
void BankAccount::computeInterest()
{
const int MONTHS_IN_YEAR = 12;
int months;
double rate = 0;
int counter = 0;
BankAccount::annualIntRate = rate;
cout << "How many months will the account be held for? ";
cin >> months;
counter = 0;
do
{
balance = accountBal * rate + accountBal;
counter++;
}while(months < counter);
cout << "Balance is:$" << accountBal << endl;
}
int main()
{
const int QUIT = 0;
const int MAX_ACCOUNTS = 10;
int counter;
int input;
int number = 0;
double balance = 0;
BankAccount accounts[MAX_ACCOUNTS];
//BankAccount display;
counter = 0;
do
{
accounts[counter].enterAccountData(number, balance);
cout << " Enter " << QUIT << " to stop, or press 1 to proceed.";
cin >> input;
counter++;
}while(input != QUIT && counter != 10);
accounts[counter].computeInterest();
system("pause");
return 0;
}
The constant field is easy enough:
class BankAccount
{
...
const static double annualIntRate = 0.03;
...
}
(Does your debugger complain about that? I'm using gcc 4.2.1) But there are other troubling things in your code, like the way computeInterest tries to set rate to zero, and the while loop... needs work.
EDIT:
One good principle is worth a hundred specific corrections. When you develop a complicated function, don't try to do it all at once; start with a simple piece, get that working perfectly, then build up. F'rinstance, computeInterest. You have several independent parts to get working: going through the while loop the correct number of times, calculating interest increments, keeping track of the balance-- right now computeInterest does none of these correctly. Tackle them one at a time, or in parallel if you want, but never combine parts that don't work.
boy it's been a LONG time since I've worked in C++, but I think all you have to do is this:
static double annualIntRate =.03;
in the "private" section of your code.
and then you can use annualIntRate as though it was a global (to each instance of the class) variable.