-
Vector adding issues...
A few topics down I mentioned I was making a program that computes the average of an unspecified amount of numbers. Here's what I have so far:
Code:
#include <iostream>
#include <string>
#include <stdexcept>
#include <vector>
using namespace std;
int main()
{
cout << "Enter the numbers you want to find the average of, followed by an end-of-file: ";
double Num;
// First vector. This holds the numbers the user has input.
vector<double>Average1;
vector<double>& Avg1 = Average1;
while (cin >> Num)
{
Avg1.push_back(Num);
}
// Second vector. This holds the amount of numbers in the first vector
typedef vector<double>::size_type Average2;
Average2 size = Avg1.size();
// Throw an error if there aren't any numers if there aren't any values stored
if (size == 0)
{
throw domain_error("Average of an empty vector");
}
// Compute the average
double Average3 = { ... I need to do this part ... } / size;
cout << "The average of the numbers is: " << Average3;
cin.get();
return 0;
}
The problem I'm facing is adding the values together in the first vector. Say, for example, I had three numbers in there, and could only hold three. I would add them together like this:
Code:
double Average3 = (Avg1[0] + [Avg1[1] + Avg1[size - 1]) / size;
If my indexes are wrong, please tell me because I've never used them before. Right, I obviously can't do the above in my program because I could be adding 2 numbers together, or 5 etc.
Simply put, how do I add together the elements in Average1 without knowing what they are, and how many there are? If that's not possible, I'll try another approach.
I welcome all criticism towards it, but please provide a solution.
Thanks.
-
-
I've never used Iterators, and don't yet know how to use them (only up to chapter 4 in Accelerated C++) Can you post the solution relevent to my program with an explanation please? I hate to ask, but I don't have my book on the C++ Standard library handy, and won't untill tomorrow night and I'd like to make changes to it during the course of tomorrow.
-
I can but I will not :) Read the FAQ on doing homework.
If you need to do this without iterators, use the size() member function and do a loop.
Code:
double total = 0;
for (size_type i = 0; i != your_vector.size(); ++i) {
total += your_vector[i];
}
-
Thanks for the solution. This isn't actually homework, I was watching a beginner's video on youtube that made an average program with three numbers, and I just wondered how to do it with an unknown amount of numbers.