c++ - Print the average of std::vector -
as title suggests i'm trying learn how print out average of vector. can done with:
int avgvec(const vector<int> & x) { int sum=0; for(int i=0; i<x.size(); ++i) { sum+=x[i];//sets sum vector size } return sum/x.size(); //now calculates average }
has been set-up correctly?
now vector in question takes input user should set as:
vector<int> myvec; int i; { cin >> i; myvec.push_back(i); }while(i>0);
has been set-up correctly?
now in order print average go making print function or after doing:
avgvec(myvec);
i'd print out myvec, or have gone in wrong way? i've executed code , in fact compute average, first number inputed, makes average 1. feel i'm right there, 1 part not clicking.
this code snippet wrong
vector<int> myvec; int i; { cin >> i; myvec.push_back(i); }while(i>0);
because enter 1 non-positive number last number of vector non-positive.
the valid code as
vector<int> myvec; int i; while ( cin >> && > 0 ) myvec.push_back(i);
the function wrong because nothing prevents vector empty. write following way
int avgvec( const vector<int> & v ) { int sum = 0; ( int x : v ) sum += x; return v.empty() ? 0 : sum / v.size(); }
Comments
Post a Comment