【发布时间】:2015-11-17 12:26:31
【问题描述】:
第一次在这里发帖。该问题要求使用函数计算并输出包含总工资、净工资等的工资单并将条件输出到文本文件中。但是我的问题是当我使用数组时函数拒绝循环。
#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;
}
【问题讨论】:
-
请出示MCVE
-
您是否收到错误消息?
-
您的函数不是“拒绝循环”,但您在循环体内有
return。因此,您在第一次执行循环后返回。 -
@Michael 正确格式化您的代码对您自己和他人都有帮助。
标签: c++ arrays string function fstream