In: Computer Science
C++ i want .00 at the output
cout << fixed << setprecision (2);where should i put this line?
quesstion
13. Array of Payroll Objects
Design a PayRoll class that has data members for an employee’s
hourly pay rate and
number of hours worked. Write a program with an array of seven
PayRoll objects. The
program should read the number of hours each employee worked and
their hourly pay
rate from a file and call class functions to store this information
in the appropriate
objects. It should then call a class function, once for each
object, to return the employee’s
gross pay, so this information can be displayed. Sample data to
test this program can be
found in the payroll.dat file.
To create the payroll.dat file, please open notepad, copy/paste the following data and save the file as payroll.dat file. Please make sure to save the file in a place where your program file is located. In otherwords, please do not hard code the path for the payroll.dat .
40.0 10.00
38.5 9.50
16.0 7.50
22.5 9.50
40.0 8.00
38.0 8.00
40.0 9.00
Mimir Requirements:
Mimir file name must be: CS939Homework8A.cpp
Here is the sample output.
Employee 1: 400.00
Employee 2: 365.75
Employee 3: 120.00
Employee 4: 213.75
Employee 5: 320.00
Employee 6: 304.00
Employee 7: 360.00
My Code
#include <iostream>
#include <fstream>
using namespace std;
class PayRoll {
private:
double hourlyPayRate;
double hoursWorked;
public:
PayRoll(double hP, double hW) {
hourlyPayRate =
hP;
hoursWorked = hW;
}
double getGrossPay() {
return hourlyPayRate *
hoursWorked;
}
};
int main() {
PayRoll** payrolls = new PayRoll * [7];
fstream myfile("payroll.dat",
std::ios_base::in);
double rate, hours;
int count = 0;
while (myfile >> rate >> hours)
{
payrolls[count++] = new
PayRoll(rate, hours);
}
for (int i = 0; i < 7; i++) {
cout << "Employee
" << (i + 1) << ": " <<
payrolls[i]->getGrossPay() << endl;
}
}
To get precision of upto 2 decimal places, we have to use 'setprecision(2)' along with 'fixed'. To get employee grosspay upto 2 decimal places, the 3rd last line has to be edited to cout << "Employee " << (i + 1) << ": " << fixed <<setprecision(2) <<payrolls[i]->getGrossPay() << endl;
Here is updated code:
#include <iostream>
#include <fstream>
#include <iomanip>
using namespace std;
class PayRoll {
private:
double hourlyPayRate;
double hoursWorked;
public:
PayRoll(double hP, double hW) {
hourlyPayRate = hP;
hoursWorked = hW;
}
double getGrossPay() {
return hourlyPayRate * hoursWorked;
}
};
int main() {
PayRoll** payrolls = new PayRoll * [7];
fstream myfile("payroll.dat", std::ios_base::in);
double rate, hours;
int count = 0;
while (myfile >> rate >> hours) {
payrolls[count++] = new PayRoll(rate, hours);
}
for (int i = 0; i < 7; i++) {
cout << "Employee " << (i + 1) << ": " <<
fixed <<setprecision(2) <<payrolls[i]->getGrossPay()
<< endl;
}
}
Code Photo:
Payroll.dat in same directory as CS939Homework8A.cpp file
Here is updated output: