Current location - Training Enrollment Network - Mathematics courses - C++, I don't know how to average the number of numbers.
C++, I don't know how to average the number of numbers.
There are three ways to do this:

1. Declare a variable for calculating numbers and a variable for input, and put them in the loop.

Include & ltiostream & gt

Use? Namespace? std

int? Master ()

{

int? sum = 0;

int? Value = 0;

int? CNT = 0;

And (cin? & gt& gt? Value)

{

Sum+= value;

cnt++

}

CIN . clear();

cout? & lt& lt? " aver:"? & lt& lt? Sum/count? & lt& lt? endl

Return? 0;

}2, declare an array, new space allocation. I don't want to write this.

3. Use standard containers, such as vector. Then the average value is calculated by calculating the sum and the length of the vector.

# include & ltiostream & gt

# include & ltvector & gt

Use? Namespace? std

Double? calc average(vector & lt; int & gt? vec)

{

int? sum? =? 0;

for(vector & lt; Int>* iterator? vIt = vec . begin(); ? Victor. = vec . end(); v t++)

sum? +=? * vIt

cout? & lt& lt? "array? VecT's? General? Yes: "? & lt& lt? sum/vec.size()? & lt& lt? endl

Return? sum/vec . size();

}

int? Master ()

{

//Initialize? By who? invest

//You can copy the data, and the data will automatically judge whether it is the second number with spaces. Now comment it out.

int? Value;

And (cin? & gt& gt? Value)

Vector. push _ back (value);

CIN . clear();

//Talk? function

Double? aver? =? calcAverage(vecT);

Return? 0;

I don't want to write because the steps are complicated. In fact, it is similar to the standard container, except that I rewrote the implementation of the container, which means there is nothing to do.

5. Personally, I suggest to write in the container of the standard container library, which is convenient to operate and can perform many other mathematical operations.

6. And (cin? & gt& gt? Value) The loop of this mode needs to be terminated by CTRL+Z. ..