程序必须循环,读入数据,计算每个员工的值,并将结果输出到文本文件。
问题是我的代码中的while循环是无限循环的,我不知道如何让它停止(在下一行不是我们正在寻找的那一点)。编译器没有发现错误,我无法在互联网上的其他地方找到可行的答案。
inFile >> employee_number >> hourly_rate >> hours_worked >> dependents >> full_time;
while (employee_number == 1)
{
count++;
PayrollMath(hours_worked, hourly_rate, base_pay, gross_pay, overtime_hours, overtime_pay, double_overtime_hours, double_overtime_pay);
IRA_Deduction = RetirementSavings(gross_pay);
mod_gross_pay = gross_pay - IRA_Deduction;
taxes_withheld = IncomeTaxWithholding(dependents, mod_gross_pay);
net_pay = mod_gross_pay - taxes_withheld;
MedicalDeductions(net_pay, full_time, medical_benefits);
number_of_employed = count;
ProgramOutput(number_of_employed, hours_worked, hourly_rate, base_pay, overtime_hours, overtime_pay, double_overtime_hours,
double_overtime_pay, gross_pay, IRA_Deduction, mod_gross_pay, taxes_withheld, net_pay, medical_benefits);
}
cout << " Successful Completion!" << endl;
outFile.close();
inFile.close();
答案 0 :(得分:0)
这是代码的简化版本,仅包含对循环行为有用的内容:
inFile >> employee_number >> hourly_rate >> hours_worked >> dependents >> full_time;
while (employee_number == 1)
{
count++;
number_of_employed = count;
}
outFile.close();
inFile.close();
在循环中,您反复检查条件是否更改为一个值,该值指示应该断开循环的时间。问题是您的条件是常量,因为在每个循环迭代期间不会修改条件中使用的变量。条件反复评估相同的值,永远不会通过改变条件给循环一个破解的机会。
while(employee_number == 1){...} // employee_number is untouched
while(true){...} // equivalent, as condition never changes (is constant)
要在某个时刻进行循环中断,您需要修改循环内条件中使用的变量。
while(employee_number == 1){... /* modifying emloyee_number */ ...}
如果我们假设您想要读取每一行,直到下一行将employee_number读为0,那么我认为您应该使用它:
while (true)
{
inFile >> employee_number >> hourly_rate >> hours_worked >> dependents >> full_time;
if (employee_number == 0) break;
number_of_employed++;
// Do your things with the line readings
}