As title suggests I'm trying to learn how to print out the average of a vector. Which can be done with:
int avgVec(const vector<int> & x)
{
int sum=0;
for(int i=0; i<x.size(); ++i)
{
sum+=x[i];//sets sum to vector size
}
return sum/x.size(); //Now calculates the average
}
Has this been set-up correctly?
Now the vector in question takes input from the user which should be set up as:
vector<int> myVec;
int i;
do
{
cin >> i;
myVec.push_back(i);
}while(i>0);
Has this also been set-up correctly?
Now in order for this to print the average would I go about making a print function or simply after doing:
avgVec(myVec);
I'd print out myVec, or have I gone about this in the wrong way? I've executed the code and it does in fact compute the average, but it only does the first number inputed, which makes the average 1. I feel like I'm right there, but one part is just not clicking.
This code snippet is wrong
vector<int> myVec;
int i;
do
{
cin >> i;
myVec.push_back(i);
}while(i>0);
because you will enter one non-positive number that is the last number of the vector will be non-positive.
The valid code would look as
vector<int> myVec;
int i;
while ( cin >> i && i > 0 ) myVec.push_back(i);
The function also is wrong because nothing prevents the vector to be empty. So I would write it the following way
int avgVec( const vector<int> & v )
{
int sum = 0;
for ( int x : v ) sum += x;
return v.empty() ? 0 : sum / v.size();
}