我正在为我的第一堂编程课做作业。我们最近开始使用文件,由于某些(可能是显而易见的)原因,我无法使我的输出正确。
程序设计为:
- 获取未知数量的房地产经纪人销售的4套房子和1套公寓。
- 将这些数字写入文件。
- 从文件中读取数据
- 计算各代理商的总销售额和平均销售额。
- 查找公司平均销售额
- 查找销售额最高的代理商。
- 显示步骤4-6.
到目前为止,这是我所拥有的。我似乎不知道如何让它显示所有代理的销售和平均。我认为它会首先显示所有代理的销售信息,公司平均水平,然后是销售最高的代理。
#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
double hSale, aSale, totalSales, companySale = 0.0, avgSales, companyAvg;
int numAgents = 0;
const int HOME_SALES = 4, APPT_SALE = 1;
char go = 'Y';
string fileName, agentName, highAgent;
ofstream outputFile;
cout << "nEnter the file name: ";
getline(cin, fileName);
outputFile.open(fileName);
while (go == 'Y' || go == 'y')
{
cout << "nEnter the agent's name: ";
cin >> agentName;
numAgents++;
outputFile << agentName << "n";
for (int a = 0; a < HOME_SALES; a++)
{
cout << "nEnter a house sale : $";
cin >> hSale;
while (hSale < 0 || hSale > 200)
{
cout << "nThe sale must be between $0.00 and $200.00. Please try again: ";
cin >> hSale;
}
outputFile << hSale << " n";
}
for (int b = 0; b < APPT_SALE; b++)
{
cout << "nEnter an appartment sale: $";
cin >> aSale;
while (aSale < 0 || aSale > 200)
{
cout << "nThe sale must be between $0.00 and $200.00. Please try again: ";
cin >> aSale;
}
outputFile << aSale << " n";
}
cout << "nEnter another agent's sales? Y for yes, N for no: ";
cin >> go;
while (go != 'Y' && go != 'y' && go != 'N' && go != 'n')
{
cout << "nError. You must enter Y or N. Please re- enter: ";
cin >> go;
}
}
outputFile.close();
ifstream textFileIn;
textFileIn.open(fileName);
if (textFileIn.fail())
{
cout << "nError. File not found. Ending program.";
cout << endl << endl;
system("pause");
return 0;
}
double higestSale = 0.0;
while (textFileIn >> agentName)
{
totalSales = 0.0;
for (int s = 0; s < HOME_SALES; s++)
{
textFileIn >> hSale;
totalSales += hSale;
}
if (totalSales > higestSale)
{
higestSale = totalSales;
highAgent = agentName;
}
companySale += totalSales;
avgSales = totalSales / HOME_SALES;
companyAvg = companySale / numAgents;
cout << setprecision(2) << fixed << endl << endl;
cout << "nAgent " << agentName << "'s total sales were $" << totalSales << " and average sales were $" << avgSales;
cout << "nThe company average sales are $" << companyAvg;
cout << "nAgent " << highAgent << " had the higest sales of $" << higestSale;
}
cout << endl << endl;
system("pause");
return 0;
}
你有两个主要的错误。
-
在写入文件后读取文件时,不读取公寓数据。尽管在计算中不需要这些数据,但它存在于文件中,需要在转到下一个代理之前读取或跳过。
-
在读循环中打印摘要。在循环完成并处理完所有代理之前,不要打印该信息。将循环的最后两行移动到循环之后的。