Reputation: 289
I have this program where it asks a user how many values the user will enter in, asks for the values and puts them into a vector. Then I need to calculate the average and standard deviation. I have the average part but it looks like something is wrong and I get the wrong average. And im not too sure how to get started on the standard deviation part.
#include <iostream>
#include <vector>
#include <cmath>
using namespace std;
int main()
{
// Create vector
vector<double> values;
// Declare variables
double count;
double value;
double average;
double stdDev;
// Prompt user and get the number of values
cout << "How many values will you enter?\n";
cin >> count;
// Get the values from user and calculate average
for( double i = 1; i<= count; i++)
{
cin >> value;
values.push_back(value);
average+=values[i];
}
cout << average/count << '\n';
//Calculate standard deviation
return 0;
}
any help is appreciated.
Upvotes: 0
Views: 1353
Reputation: 1970
Use double average = 0;
instead of double average;
And use values[i-1]
instead of values[i]
inside the loop.
Why?
You declared average and didn't initialized it. For this it has a value that can't be known before the code executes. When you are adding value[i]
with average
that value of average
is in it. For this you are getting wrong output. You need to add only all value[i]
. So initialize average
with 0.
Vector indexing is 0 based. So the n-th element inserted to a vector will be found at [n-1]-th position.
Upvotes: 2