C++ 读取文本文件获取奇怪值,输出无限值
该计划输出的女生平均GPA为:-1.IND,而不是实际输出的GPA。My.dat文件的格式如下: f 2.4 f 2.6 m 3.5 等 我想让它输出这些值的平均GPA,但变量avgfGPA和avgmGPA的结果是-1.INDC++ 读取文本文件获取奇怪值,输出无限值,c++,visual-studio-2010,C++,Visual Studio 2010,该计划输出的女生平均GPA为:-1.IND,而不是实际输出的GPA。My.dat文件的格式如下: f 2.4 f 2.6 m 3.5 等 我想让它输出这些值的平均GPA,但变量avgfGPA和avgmGPA的结果是-1.IND #include <iostream> #include <iomanip> #include <fstream> using namespace std; void openFiles(ifstream& inFile,
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
void openFiles(ifstream& inFile, ofstream& outFile)
{
inFile.open("finalin.dat");
outFile.open("finalout.dat");
outFile << fixed << showpoint << setprecision(2);
inFile >> fixed >> showpoint >> setprecision(2);
if (!inFile||!outFile)
{
cout << "Problem opening file.";
}
}
void initialize(int &countFemale,int &countMale,float &sumFemaleGPA,float &sumMaleGPA)
{
countFemale=0;
countMale=0;
sumFemaleGPA=0;
sumMaleGPA=0;
}
void sumGrades(ifstream& inFile, float &sumFemaleGPA, float &sumMaleGPA,int &m,int &f)
{
sumFemaleGPA=0;
sumMaleGPA=0;
if (!inFile)
{
inFile.open("finalin.dat");
}
char sex;
float grade;
while(!inFile.eof())
{
inFile >> sex >> grade;
switch (sex)
{
case 'f': sumFemaleGPA= (sumFemaleGPA + grade);
f++;
break;
case 'm': sumMaleGPA= (sumMaleGPA + grade);
m++;
break;
}
}
void averageGPA(float &avgfGPA, float &avgmGPA, int &m, int &f, float &sumFemaleGPA, float &sumMaleGPA)
{
avgmGPA=0;
avgfGPA=0;
avgfGPA=sumFemaleGPA/f;
avgmGPA=sumMaleGPA/m;
}
void printResults(float &avgfGPA, float &avgmGPA, ofstream& outFile)
{
cout <<"The average GPA of the female students is: "<< avgfGPA << endl;
cout <<"The average GPA of the male students is: "<< avgmGPA;
outFile << "The average GPA of the female students is: "<< avgfGPA << endl;
outFile <<"The average GPA of the male students is: "<< avgmGPA;
}
int main()
{
int countFemale;
int countMale;
float sumFemaleGPA;
float sumMaleGPA;
float avgfGPA;
float avgmGPA;
ifstream inFile;
ofstream outFile;
openFiles(inFile,outFile);
initialize(countFemale,countMale,sumFemaleGPA,sumMaleGPA);
sumGrades(inFile,sumFemaleGPA,sumMaleGPA,countMale,countFemale);
averageGPA(avgfGPA,avgmGPA,countMale,countFemale,sumFemaleGPA,sumMaleGPA);
printResults(avgfGPA,avgmGPA, outFile);
}
您的问题在于引用或缺少引用: 此代码: void averageGPAfloat avgfGPA,float avgmGPA,int m,int f,float sumFemaleGPA,浮点sumMaleGPA{avgmGPA=0;avgfGPA=0 avgfGPA=sumFemaleGPA/f;avgmGPA=sumMaleGPA/m;} 应该是 …删除了解决方案作业
<> P>更清楚的是,C++与java不同,如果你想通过值改变别处的< /P>,你仍然犯了与前一个问题相同的错误。你可能应该首先应用这些修正。我改变了这些变量,但是它仍然没有给我想要的解决方案。我怀疑它可能与.eof或while循环有关?请检查您的while!eof循环非常小心…我通过添加引用编辑了以前的代码,但仍然得到不正确的奇数值。我看不出还发生了什么,我怀疑这可能是.eof或while循环的问题。我的教授建议我们使用.eof来读取长度未知的文件。请阅读我在您的OP上关于读取文件内容背后逻辑的评论。它应该和你写的有点不同。太好了!祝你学习顺利!