我被困在这个程序的点上,我要计算所有 CarType 的价格总和。例如。福特的价格总和是__。数据是从名为 input.dat 的文件中提取的。我一生都无法弄清楚如何对某种汽车类型的所有元素进行分组并将总和相加,然后将总和存储到数组 carPriceSum 中。我了解如何找到数组中连续元素的总和。任何提示或示例将不胜感激!
// carstats.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <iomanip>
#include <string>
#include <conio.h> // I understand this is not best practice
#include <fstream>
using namespace std;
enum CarType
{
Ford,
Chevy,
Honda,
Toyota
};
struct CarCustomer
{
string firstName;
string lastName;
double price;
CarType carType;
};
void calcCarStats(CarCustomer arrCustomers[], int count, int carCount[], double carPriceSum[])
{
for(int index = 0; index < count; index++)
{
carCount[arrCustomers[index].carType]++;
carPriceSum[index] = arrCustomers[index].price;
// This is where I'm stuck
}
}
void displayCarTypeCounts(int carCount[], double carPriceSum[])
{
for(int index = Ford; index <= Toyota; index++)
{
cout << carCount[index] << " " << carPriceSum[index] << endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int count = 0;
CarCustomer arrCustomers[100]; //Array of structs for the Struct CarCustomer
CarCustomer carCustomer;
int carCount[100] = {0};
double carPriceSum[100] = {0.0};
double carPriceAvg[100] = {0.0};
ifstream fin;
CarType carType; //CarType enum
fin.open("input.dat");
if(!fin)
{
cout << "Error opening file, check the file name" << endl;
_getch();
return -1;
}
while (!fin.eof())
{
int carTypeInt;
fin >> arrCustomers[count].firstName;
fin >> arrCustomers[count].lastName;
fin >> arrCustomers[count].price;
fin >> carTypeInt;
arrCustomers[count].carType = (CarType)carTypeInt;
count++;
}
fin.close();
calcCarStats(arrCustomers, count, carCount, carPriceSum);
displayCarTypeCounts(carCount, carPriceSum);
_getch();
return 0;
}
//input.dat
Joe Smith 5999.99 0
Mary Doe 23999.99 1
Joe Green 1999.99 1
Jim Smith 4999.99 2
Jane Green 3999.99 0
Mark Doe 9999.99 1
John Peters 7999.99 2
Jim Green 8999.99 3
Mindy Doe 3999.99 2
Janet Green 6999.99 1
Mork Doe 2999.99 3
Jane Smith 3999.99 3
John Roberts 15999.99 1
Mandy Doe 12999.99 0
Janet Smith 6999.99 0
Macy Doe 14999.99 1