[C++} Not sure if this is even possible - c++

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.

Related

Calculations wont display in output

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;
}
}

Issues with PrintStub() Function's ouput

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;
}

Why is my output wrong?

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double COUNTY_TAX = 0.02;
const double STATE_TAX = 0.04;
double totalSales;
void countyTax(double newCountyTax);
void stateTax(double newStateTax);
void total(double newTotal);
int main ()
{
cout << "Please enter the total dollar amount of sales: $";
cin >> totalSales;
countyTax(1);
stateTax(1);
total(1);
return 0;
}
void countyTax(double newCountyTax)
{
double newCountyTaxA;
newCountyTaxA = totalSales * COUNTY_TAX;
cout << "The county tax is: $" << newCountyTaxA << endl;
}
void stateTax(double newStateTax)
{
double newStateTaxA;
newStateTaxA = totalSales * STATE_TAX;
cout << "The State tax is: $" << newStateTaxA << endl;
}
void total(double newTotal)
{
double newTotalA, newStateTaxA, newCountyTaxA;
newTotalA = newStateTaxA + newCountyTaxA;
cout << "The total is: $" << newTotalA << endl;
}
hello guys! I am getting into modules in C++ and the above code compiles correctly but I can't seem to figure out why my output is wonky. I get the county tax and state tax to show properly but when the total shows I get "$nan" i was wondering if i could get some feedback on this? does it possibly have to do with the fact that within the module i am not using any global variables like i do with the totalSales and COUNTY_TAX and SALES_TAX and that when i declare newTotalA newStateTaxA newCountyTaxA they are declared but not assigned? just a tad confused here..THANKS!!!
the variables newStateTaxA and newCountyTaxA that are created and computed in countyTax and stateTax are local to those functions. Once the functions complete, those variables, and the values they contain, go away. In total you create new local variables with the same names. These have no relationship with the previously defined variables, apart from sharing names, and will not store the values previously computed in the other two functions.
The easiest solution, although not considered the most robust, is to create the two variables at the global scope, along with totalSales so that the values that they are assigned to in the two functions persist.
If you do not wish to use global variables (which I also don't care to use), you can declare them in your main function, and modify your other functions to return the calculated values:
double countyTax(double newCountyTax)
{
double newCountyTaxA;
newCountyTaxA = totalSales * COUNTY_TAX;
cout << "The county tax is: $" << newCountyTaxA << endl;
return newCountytaxA;
}
The calls in main() would then read:
newCountyTaxA = countyTax(1);
Your are doing a fundamental mistake here in the following code :
void total(double newTotal)
{
double newTotalA, newStateTaxA, newCountyTaxA;
newTotalA = newStateTaxA + newCountyTaxA;
cout << "The total is: $" << newTotalA << endl;
}
The Variables that you have created here "newStateTaxA", and "newCountyTaxA" does not have any relation to the other variables that you have created and assigned in the other methods, they are local for each method. You need to either make them global or return valued from those functions.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
const double COUNTY_TAX = 0.02;
const double STATE_TAX = 0.04;
double totalSales;
void Taxes();
int main ()
{
cout << "Please enter the total dollar amount of sales: $";
cin >> totalSales;
Taxes();
return 0;
}
void Taxes()
{
double countyTax, stateTax, total;
countyTax = totalSales * COUNTY_TAX;
stateTax = totalSales * STATE_TAX;
total = countyTax + stateTax;
cout << "The County Tax is: $" << fixed << setprecision(2) << countyTax << endl;
cout << "The State Tax is: $" << fixed << setprecision(2) << stateTax << endl;
cout << "The total is: $" << fixed << setprecision(2) << total << endl;
}
here is what I came up with. Everything works and outputs as desired. I guess now I am wondering if this type of setup with one module and multiple calculations inside it considered good programming?

no candidates for error compile error

I am trying to compile my application and it keeps running into "no match for 'operator<<'... it is not clear what the exact error of the program seems to be because he object is configured correctly as far as I can see.
#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;
float setLoan(void); //mutator
float setIntrest(void); //mutator
float setYears(void);
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;
}
float MortgageCalc::setLoan(void)
{ //returns loan amt to private member
return loan;
}
float MortgageCalc::setIntrest(void)
{ //returns interest amt to private member
return interest;
}
float MortgageCalc::setYears(void)
{ //returns years to private member
return years;
}
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;
};
cout << "Total payment plus Interest will be " << i.plusInterest << "." << endl;
plusInterest is a class method pointer. Unsurprisingly, std::ostream has no clue what to do with a class method pointer, and is rightfully voicing its very strong objection, to such a preposterous proposition that it knows what to do with some strange class's method pointer.
You probably meant to write:
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
Now, that's a proper function call, that returns an int, and std::ostream is now delighted to take this int, and do its magic with it.

In C++ for the use of arrays within functions, where data is entered into arrays from a .txt file using ifstream

First time posting here. The question asks to use functions to calculate and out put into a table a payroll with gross, netpay and the like as well as output a condition into a text file. However my issue is with the functions refusing to loop when I use arrays.
#include <iostream>
#include <fstream>//File stream
#include <string> //For use with string variables
#include <iomanip>//For use with formatting
double hoursworked[6],hourlyrate[6];
int i;
using namespace std;
double gross_fun(double hourlyrate[], double hoursworked[],int &numofelements)
{
double overtime[6];
double gross[6];
for(i=0; i<=5; i++){
if (hoursworked[i] > 40){
overtime[i] = 1.5*hourlyrate[i] * (hoursworked[i]-40); //Overtime is 1.5 times hourly rate
gross[i]=overtime[i]+(40*hourlyrate[i]);
}
else
gross[i]= hourlyrate[i] * hoursworked[i];
return gross[i];
}
}
double taxes_fun(double gross[], int &numofelements)
{
double taxes;
for(i=0; i<=5; i++){
taxes = .1 * gross[i];
return taxes;
}
}
double SS_fun( double gross[], int &numofelements)
{
double social;
for(i=0; i<=5; i++){
social = .05 * gross[i];
return social;
}
}
double netpay_fun(double gross[], double tax[], double social[], int &numofelements)
{
double netpay;
for(i=0; i<=5; i++){
netpay= gross[i] - (tax[i] + social[i]); //Resultant net pay given when taxes and security are subtracted
return netpay;
}
}
double taxes(double tax[], int &numofelements);
double social_security (double social[], int &numofelements);
double netpay_fun (double netpay[], int &numofelements);
double gross_fun(double hourlyrate[], double hoursworked[], int &numofelements);
int main ()
{
ifstream inFile; //To read .txt file
inFile.open ("input.txt");
if (inFile.fail()){
cerr << "Error Opening File" << endl;
exit(1);
}
int EmpNum[6];//Employee Number
int i = 0; //Counter
double gross[6],taxes[6],socia[6],netpay[6],moneytopay[6];
double overtime[6],hoursworked[6],hourlyrate[6],social[6],totalnetpay = 0.0f;
char paytype[6];
string firstname[6],lastname[6];
cout << setprecision(2) << fixed; //Set double values to two decimal places
(inFile>>EmpNum[i]>>firstname[i]>>lastname[i]>>hoursworked[i]>>hourlyrate[i]>>paytype[i]){
i++;
}
for(i=0;i<=5;i++){
gross[i]=gross_fun(hourlyrate, hoursworked, i);
taxes[i] = taxes_fun(gross, i);
social[i] = SS_fun (gross, i);
netpay[i] = netpay_fun (gross, taxes, social, i);
totalnetpay=totalnetpay+netpay[i];
}
}
cout << setw(6) << "EmpNo"<< setw(13) << "First Name"<< setw(13) << "Last Name"<< setw(8) << "Gross";
cout << setw(8) << "Tax"<< setw(8) << "SS"<< setw(10) << "Net Pay"<< setw(9) << " Payment Type";
for(i=0;i<6;i++){
cout << setw(5) <<EmpNum[i]<< setw(11) <<firstname[i]<<setw(14) <<lastname[i]<< setw(11) << gross[i]<< setw(8) << taxes[i];
cout << setw(9) << social[i]<< setw(8) << netpay[i]<< setw(7) << paytype[i]<< endl;
}
cout<<"\nSum of netpay: "<<totalnetpay;
return 0;
}
The reason is simple, you have put you return statement inside your for loop. Just move it out.
double gross_fun(double hourlyrate[], double hoursworked[],int &numofelements) //Function to determine gross salary
{
double overtime[6];
double gross[6];
double total = 0.0;
for(i=0; i<=5; i++){
if (hoursworked[i] > 40){ //Calculating gross salary if hours worked greater than 40
overtime[i] = 1.5*hourlyrate[i] * (hoursworked[i]-40); //Overtime is 1.5 times hourly rate
gross[i]=overtime[i]+(40*hourlyrate[i]);
}
else
gross[i]= hourlyrate[i] * hoursworked[i]; //Calculating gross salary if no overtime is done
// remove here
}
return // something
}
You have done the same thing inside all your functions. If you want to return an array, i suggest you pass it in the parameters and return void. or return an array.