Here is what you need to do.
Step 1: You need 3 variables. A
int input;
to hold the number the user enters. A
int sum;
to hold the sum of all the numbers the user entered. A
int average;
to hold the average of all the numbers.
Step 2: Get user input in a loop, if you want to get 10 numbers you can do something like this
for (int i = 0; i != 10; ++i)
. That will loop through 10 times. Now every time through the loop you should ask the user for a number, store that number in the input variable. After you do that you need to add whatever the user entered to the sum variable like so
sum += input;
.
Step 3: After the user is done entering numbers it is time to find the average. This is very easy actually. All we need to do is divide the variable sum by the number of numbers entered by the user which in the case above is 10. So
average = sum / 10;
And boom we have the average.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
// How many numbers to enter
const int numToEnter = 10;
int main()
{
int sum = 0;
int average = 0;
int input;
// Get 10 numbers from the user
for (int i = 0; i != numToEnter; ++i)
{
cout << "Enter a number: ";
cin >> input;
sum += input;
}
// Get average and print it
average = sum / numToEnter;
cout << "The average is: " << average << endl;
return 0;
}
|