所以我对这个程序的目标是从文件读取输入并根据对读取的信息进行的计算将结果输出到文件。我一直遇到的问题是我在输出文件中不断得到相同的结果。
答案 0 :(得分:0)
整数舍入。这似乎是一个问题。从使用int
切换为使用double
。
答案 1 :(得分:0)
首先请注意,我使用的是Visual Studio和预编译的标头,因此我的标头配置略有不同。
当我编译你的代码时,编译器确实警告我使用“int”将是一个问题。我总是删除警告,除非我确定我不需要,我不会忽略警告,除非我确信我可以安全。
对于“employee.h”,我有:
#pragma once
using namespace std;
class employee
{
public:
void readData(ifstream& inf);
//Precondition: File must exist, be accessible, and have the appropriate contents
//Postcondition: The contents in the file are assigned to a variable.
void Compute(double basepay);
//Precondition: basepay = $800
//Postcondition: Salary is found using the basepay plus the three other basepays percentages.
void print(ofstream& outf) const;
//Precondition: The new values (ID and salary) must be updated and accessible.
//Postcondition: The ID and salary must be displayed in an output file. The salary must be in the proper format.
employee();
//Precondition: The variables ID, Job_class, Years, Ed, and sal must have been created already.
//Postcondition: the variables ID, Job_class, Years, Ed, and sal are all set to zero.
private:
int ID;
int Job_class;
int Years;
int Ed;
double sal;
};
请注意,“sal”是双倍的。
对于“employee.cpp”,我有:
#include "stdafx.h"
#include "employee.h"
using namespace std;
void employee::readData(ifstream& inf)
{
inf >> ID >> Job_class >> Years >> Ed;
}
void employee::Compute(double basepay)
{
//int extra = .01;
//int bp1 = 0;
//int bp2 = 0;
//int bp3 = 0;
double extra = .01;
double bp1 = 0;
double bp2 = 0;
double bp3 = 0;
if (Job_class == 1)
{
bp1 = basepay*.05;
}
if (Job_class == 2)
{
bp1 = basepay*.10;
}
if (Job_class == 3)
{
bp1 = basepay*.20;
}
if (Years > 0 && <= 10)
{
bp2 = basepay*.05;
}
if (Years> 10)
{
bp2 = basepay*(.05 + extra);
}
if (Ed == 1)
{
bp3 = 0;
}
if (Ed == 2)
{
bp3 = basepay * 05;
}
if (Ed == 3)
{
bp3 = basepay*.12;
}
if (Ed == 4)
{
bp3 = basepay*.20;
}
sal = basepay + bp1 + bp2 + bp3;
}
void employee::print(ofstream& outf) const
{
outf << ID << setw(15) << fixed << showpoint << setprecision(2) << "$ " <<
sal << endl;
}
employee::employee() // default constructor
{
ID = 0;
Job_class = 0;
Years = 0;
Ed = 0;
sal = 0.0;
}
主要是我:
#include "stdafx.h"
using namespace std;
#include "employee.h"
int main()
{
double basepay = 800;
employee emp;
ifstream inf;
inf.open("G:\\Temporary\\employee.txt");
ofstream outf;
outf.open("G:\\Temporary\\employeeout.txt");
if (!inf)
{
cout << " *** Input file does not exist! *** " << endl;
return 1;
}
outf << "ID #" << setw(20) << "Salary" << endl;
outf << "****************************" << endl;
while (!inf.eof())
{
emp.readData(inf);
emp.Compute(basepay);
emp.print(outf);
}
inf.close();
outf.close();
return 0;
}
对于“employee.txt”我有:
1078 2 12 3
1070 3 10 4
请注意,没有逗号。
对于“employeeout.txt”,我有:
ID # Salary
****************************
1078 $ 1024.00
1070 $ 1160.00
1070 $ 1160.00
请注意,程序正在读取最后一行两次。我没有解决这个问题;我认为这是个人喜好的问题,如何处理,以便你可以按照自己的方式去做。