Hopefully you can kind of see where Im going with this. FICA at 7.65%, FedTax at 22 or 28% depending on the amount made, and state tax at 12%. I have to make all of these functions come to an output of:
Name earned $645.00
FICA $xxx.xx
Fed $xxx.xx
State $xxx.xx
Net Pay $xxx.xx
So I believe mathematically I am there, its just setting up for success is where Iam genuinely stuck.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int hourRate, hourWork, otHours, pay, FICA, state, fed, netpay;
void Pause()
{ string junk, extraNewLine;
cin.ignore();
cout << "Press Enter to continue ... ";
getline(cin, junk);
}
void GetPay(){
pay = (hourRate * hourWork) + (otHours * (hourRate * 1.5));
cout << pay;
}
void GetHrs(){
cout << " Hours worked? ";
cin >> hourWork;
if (hourWork > 40){
otHours = hourWork - 40;
hourWork - otHours;
}
else {
otHours = 0;
}
}
void GetRate(){
cout << "Hourly Rate? ";
cin >> hourRate;
}
void CalcFCIA(){
FICA = pay *.0765;
cout << FICA;
}
void CalcFedTax(){
if (pay > 1500){
fed = pay * .28;
}
else {
fed = pay * .22;
}
}
void CalcStateTax(){
state = pay * .12;
cout << state;
}
void PrintStub(){
cout << "FICA $" + FICA;
cout << "Fed $" + fed;
cout << "State $" + state;
netpay = pay - (FICA + fed + state);
cout << "Net Pay" + netpay;
}
int main()
{
string name;
cout << "Employee name? ";
cin >> name;
GetRate();
GetHrs();
PrintStub();
Pause();
}
My output is not displaying any integers. I am only getting:
FICA $Fed $State $Net Pay
You don't appear to be calling any of the Calc functions. Each of them will have to be called in order to have any effect.
Also, it will likely help you follow the logic to write functions that return values rather than operating on global variables -- it makes the transformations you're doing on the data much more explicit. For example, you could use functions like:
int CalcFICA(int pay){
return pay * .0765;
}
Related
I'm a student in a basic programming class and I'm trying to complete this program for a class assignment. It's a simple program that calculates compounded interest by the inputs of the user. However, when writing the code, I noticed that the the result is 0 even though based on the input I would expect otherwise. Could anyone tell me why the program isn't showing results?
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
Yes. You are not calling the futureValue function which would compute the value for you. Due to the value not being computed, it remains 0. Fix:
#include <iostream>
#include <cmath>
using namespace std;
// Declarations of Prototype
void futureValue(double* presentValue, float* interestRate, int* months, double* value);
// List of variables
double presentValue = 0;
float interestRate = 0;
double value = 0;
int months = 0;
// Start of Main function
int main(void)
{
cout << "What is the current value of the account?";
cin >> presentValue;
cout << "How many months will Interest be added to the account?";
cin >> months;
cout << "And what will be the Interest Rate of the account?";
cin >> interestRate;
futureValue(); //Here we compute the value
cout << "After " << months << " months, your account balence will be $" << value << ".";
return 0;
}
void futureValue()
{
if (presentValue <= 0)
{
cout << "I'm sorry, you must have a current balence of more than 0.00 dollars to calculate.";
return;
}
else
{
value = presentValue * pow(interestRate + 1, months);
return;
}
}
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 have created an solution that compiles correctly, but when I enter in the required input it provides only a value of '0' which is not correct. It started when I amended the code to have exception handling but for some reason now, the code no longer processes. The first three input values can be anything and it will still output '0' when run. Thoughts?
#include <iostream>
#include <cmath>
#include <string>
#include <sstream>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
private:
double loan, interest;
int years;
public:
MortgageCalc() = default;
void setLoan(double l) { loan = l; } //mutator
void setIntrest(double i) { interest = i; } //mutator
void setYears(short y) { years = y; } //mutator
double getMonthlyDue(double term) { return ((loan * ((interest / 100) / 12) * term) / (term - 1)); } //constructor to run math calculation on montly loan amou
double getTotalDue(double term) { return (getMonthlyDue(term) * (years * 12)); } //constructor to compute total amount with interest
double getTotalInt(double term) { return (getTotalDue(term) - loan); }
};
int main()
{
MortgageCalc mort1;
int choice = 0;
int years = 0;
double term(0), loan(0), interest(0);
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
// cout << "Loan amount cannot be negative. Enter the amount: ";
mort1.setLoan(loan);
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest; {
if (interest <= 0) { //example if you put 0 or negative # an exception will throw
throw std::invalid_argument("received negative value"); //example #2 of negative throw exception
}
}
// cout << "Interest rate cannot be negative. Enter the amount: ";
mort1.setIntrest(interest);
cout << "Enter the length of the loan in years: "; //establishes term of payments
while (!(cin >> years) || years < 0)
cout << "Remainder of loan period cannot be negative. Enter the amount: ";
mort1.setYears(years);
term = pow((1 + ((interest / 100) / 12)), (12 * years)); //simple interest calculation with power calc to establish whole number translation
while (choice != 3) //loop for menu options and clean function exit
{
cout << endl;
cout << "Program to Calculate Mortgage Payments" << endl <<
"1. Monthly Payment" << endl <<
"2. Total Payment" << endl <<
"3. Exit" << endl << endl <<
"Enter an option above: ";
cin >> choice;
if (choice == 1)
cout << "Monthly payment due is " << mort1.getMonthlyDue(term) << "." << endl;
else if (choice == 2)
cout << "Total amount for entire loan payments plus interest is $" << mort1.getTotalDue(term) << "." << endl <<
"Total Interest Paid for this loan amount $" << mort1.getTotalInt(term) << "." << endl;
}
return 0;
}
Your problem is that when you do
mort1.setLoan(loan);
loan will always be 0 unless cin >> loan; throws an std::sting. When you use
{
std::string loan;
try
{
cin >> loan;
}
catch (string loan) //Exception for comma in 'loan' input by user
{
if (loan.find_first_not_of("0123456789.") != std::string::npos) // npos invalid pseudo-index
{
std::cerr << "bad input, must use whole numbers only\n" << endl;
return 1;
}
std::istringstream ins(loan); // Converts the string into a number without punctuation
ins >> loan;
}
}
You have your conversion code from a string into the double1 in the catch statement. You will only ever enter that statement if cin >> loan; throws a std::string which I do not believe will ever happen. Since you never actually update the value of loan in main it stays at the 0 you initialized it with.
You should only be doing error handling in the catch block. The code to convert the string to a double should be handled outside the catch block. I think you need to revisit how exceptions work and you should also look into how scopes can hide names from the outer scope.
1 This is also not going to work since you are hiding the double loan from main with the string loan declared inside the sub scope. You need to use different names for the variables in the sub scope.
I'm trying to find the average net pay for a payroll program. What I'm wondering is it possible to create an array from the outputted tabular data and use the array to calculate the average? Or do I have to do this a different way? My code thus far:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class employee {
ifstream fin;
char employeeid[12];
char employeename[20];
char martialstatus;
int hoursworked, overtime;
double hourlyrate, overtimepay, regularpay, grosspay, taxrate, taxamount, netpay, average;
void calculateGrosspay();
void calculateTax();
void calculateNetpay();
void printHeadings();
void printData();
double findAverage();
void printAverage();
public: employee();
~employee();
void printReport(); };
employee::employee(){
fin.open(payrollData.txt);
}; //Constructor
employee::~employee() {
fin.close(); } //Destructor
void employee::calculateGrosspay() {
if (hoursworked > 40) {
overtime = hoursworked - 40;
regularpay = hoursworked * hourlyrate;
overtimepay = overtime * (hourlyrate * 1.5);
grosspay = regularpay + overtimepay;
}
else grosspay = hoursworked * hourlyrate;
} //Calculate gross pay function
void employee::calculateTax() {
taxrate = .30;
taxamount = grosspay*taxrate;
} // calculate tax function
void employee::calculateNetpay() {
netpay = grosspay - taxamount;
} //Calculate net pay
void employee::printHeadings() {
cout << setw(45) << "-Employee Payroll Report-" << endl;
cout << "____________________________________________________________" << endl;
cout << "NAME ID HW OT RT-PAY OT-PAY Gross Tax NetPay" << endl;
cout << "____________________________________________________________" << endl;
} // print table headings
void employee::printData() {
cout << setprecision(2) << setiosflags(ios::fixed | ios::showpoint);
cout << setw(6) << employeename << setw(12) << employeeid << setw(4) << hoursworked << setw(3) << overtime << setw(8) << regularpay << setw(8)
<< overtimepay << setw(8) << grosspay << setw(8) << taxamount << setw(8) << netpay << endl;
} // print data
void employee::printReport() {
int i = 0;
printHeadings();
while (fin >> employeename >> employeeid >> hoursworked >> hourlyrate) {
calculateGrosspay();
calculateTax();
calculateNetpay();
printData();
i++;
}
}
double employee::findAverage() {
return average;
}
void printAverage() {
cout << endl;
cout << "The average netpay is" << average << endl;
}
void main() {
employee.printReport();
employee.findAverage();
employee.printAverage();
}
So after the program has printed the data to the console I want to find the average of the net pays and print it to the console. Best way to do this?
You'll probably need a vector like Soren mentioned. If you're trying to get some averages for all employees (which that's what I assume you're trying to do), then let's say we're going to try and get an average for gross pay.
You'll need a vector global, like such:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <vector>
using namespace std;
vector<double> netPayList;
double globalAverage;
You'll then need to add information to the vector when GrossPay is calculated as such:
void employee::calculateNetpay()
{
netpay = grosspay - taxamount;
netPayList.push_back(netpay);
}
Finally, we can calculate the average in employee::findAverage(), we should also probably use a for loop for this as well, and in my opinion we should ditch the public function of "employee" and switch that over to a traditional function, since we are trying to get the average for many "employee" instances. The average calculation will now look like this:
double findAverage()
{
for (int iterator = 0; iterator < netPayList.size(); iterator++)
{
average += netPayList[iterator];
}
globalAverage /= netPayList.size();
return globalAverage;
}
Anyway, that's basically the gist of it. Keep working on your stuff, but also I would suggest that you title your questions better. Someone with more gumption and SO privileges than I will most likely edit your OP.
I'm very new to writing functions. This is my first attempt at using call by reference parameters specifically for a homework assignment. This program should calculate how long it takes to pay off a loan based on the users input of the amount they borrow, their monthly payment and the interest rate. The program should make sure the user doesnt input a payment number less than monthly interest amount and check for negative integers etc.
The area I commented out was my first go before i attempted to turn all of that into a function that uses call by reference parameters. At that point the program ran fine and i got output within a dollar of what I was looking for. After i rewrote the program like this and tried to make it a function, the program compiles but break to the bottom cout statements after asking for the interest rate. I assume my problem is somewhere within the interest1 function where i convert the percent to a decimal but i cant figure out why it would skip the rest of the functions afterwards.
Thanks for any advice you might have on this issue or anything else that looks wrong with the program itself.
#include <iostream>
#include <fstream>
using namespace std;
double amount();
double interest1();
double pay(double amt, double interest);
void payoff(double monthly, double Minpayment,double borrow,double interest, double&
totalinterest,int& month);
int main()
{
double monthly,month,totalinterest;
cout << fixed;
cout <<showpoint;
cout <<setprecision(2);
double borrow=amount();
double interest=interest1();
double Minpayment=pay(borrow, interest);
void payoff(double monthly,double Minpayment,double borrow,double interest,double&
totalinterest,int& month);
/*
// cout << "What is the monthly payment amount? \n";
// cin >> monthly;
// if(monthly<Minpayment)
// {
// cout << "You must make payments of at least: " << Minpayment++ << endl;
// cout << "Because your monthly payment is " << Minpayment << endl;
// cout << "Dont get overwhelmed with debt!!!!!! \n";
// }
// else
//
// {
// int month = 1;
// double totalinterest=0;
// do
// {
// double Minpayment=pay(borrow, interest);
// borrow=(borrow+Minpayment)-monthly;
// totalinterest=totalinterest+Minpayment;
// month++;
// }while(borrow>monthly);
*/
cout << "Your debt will be paid off in " << month << " months \n";
cout <<" with a final payment of " << borrow << endl;
cout << "You paid " << totalinterest << " in interest. \n";
return 0;
}
double amount()
{
double borrow,amt;
do
{
cout << "How much money do you want to borrow? \n";
cin >> amt;
if(amt<1)
cout << "You must enter a positive number!";
}while(amt<1);
borrow = amt;
return borrow;
}
double interest1()
{
double rate;
do
{
cout << "What is the annual interest rate expressed as a percent? \n";
cin >> rate;
if(rate<1)
cout << "You must enter a positive number!";
}while(rate<1);
double interest = (rate/12)*.01;
return interest;
}
double pay(double borrow,double interest)
{
double Minpayment=borrow*interest;
return Minpayment;
}
void payoff(double monthly,double Minpayment,double borrow,double interest, double&
totalinterest,int& month)
{
cout << "What is the monthly payment amount? \n";
cin >> monthly;
if(monthly<Minpayment)
{
cout << "You must make payments of at least: " << Minpayment++ << endl;
cout << "Because your monthly payment is " << Minpayment << endl;
cout << "Dont get overwhelmed with debt!!!!!! \n";
}
else
{
int month = 1;
do
{
double Minpayment=pay(borrow, interest);
borrow=(borrow+Minpayment)-monthly;
double totalinterest=totalinterest+Minpayment;
month++;
}while(borrow>monthly);
}
}
When you call a function inside main, you don't need to specify parameter types anymore:
void payoff(double monthly,double Minpayment,double borrow,double interest,double&
totalinterest,int& month); //wrong
should be
payoff(monthly, Minpayment,borrow, interest, totalinterest, month);
You should put double& andint& to the function's parameter list when define the function like you did.