該計劃輸出「女學生的平均GPA是:-1。#IND」,而不是實際應該輸出的內容。我的.dat文件的格式如下:
˚F2.4
˚F2.6 米3.5
等 我希望它輸出的值的平均GPA,但變量「avgfGPA」和「avgmGPA」都結束了爲 「-1#IND。」獲取奇怪的值讀取文本文件,獲得無限值輸出
#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);
}
你仍然犯上一個問題的錯誤。您應該首先應用這些更正。 – Mysticial
我改變了這些變量,但它仍然沒有給我我想要的解決方案。我懷疑它可能是.eof,或while循環? –
仔細檢查while(!inFile.eof)循環... – AndyG