hello everyone. i got a question here.. i need to create a program to prompt the user to enter the values and find the average of these values.. can u guys have a look on it and gives some advises to solve this problems...
#include <iostream>
using namespace std;
int main()
{
int n,average;
cout<<"Enter the number of values"<<endl;
cin>>n;
for(int i=1;i<=n;i++)
{
int average,value;
cin>>value;
value+=value;
average=value/n;
cout<<average<<endl;
}
system("pause");
return 0;
}
the program can execute but the output is always zero, can u correct it for me? thanks:)
int main()
{
int n;
double average(0); // <- NOTE
std::cout << "Enter the number of values" << std::endl;
std::cin >> n;
for(int i = 0; i < n; ++i) {
int value;
std::cin >> value;
average += value;
}
average /= n;
std::cout << average;
}
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;
// How many numbers to enter
constint 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;
}
Gezz you guys really need better naming conventions ;p it looked like you were trying to do a newline totally few over my head he was dividing. That is also another reason why I like to put spaces between operators and operands.