Need help with the C++ programming. I am trying to compute the count of values, the average, and the standard deviation of the input given by user. My output is correct except for the standard deviation. My code is below:

Thanks

``````#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{

bool more = true;
int count = 0;
double sum = 0;

cout << " Enter a value: (CTRL-D to quit): ";
float num = 0.0;
cin >> num;
while (true)
{
++count;
cout << count << endl;
sum += num;
cout << " Enter a value: (CTRL-D to quit): ";
cin >> num;
if  (cin.eof())

{
break;
}
}

double avg = 0;
avg = sum / count;

double s_dev = 0;
s_dev = sqrt( (( pow(sum,2.0)) -(( 1.0/count) * (pow(sum,2.0))))/ (count -1.0));
cout << endl << endl;
cout << " There are " << count << " values. " << endl;
cout << " The average is:  " << avg << endl;
cout << " The standard deviation is:  " << s_dev << endl;

return 0;
}``````

<< moderator edit: added code tags: [code][/code] >>

You aren't using the std dev formula correctly.

Also, here is an update to your code. Notice all the variables are declared at the top of main. Notice how …

## All 3 Replies

You aren't using the std dev formula correctly.

Also, here is an update to your code. Notice all the variables are declared at the top of main. Notice how the code is indented. The program is easier to read now.

Take care,
Bruce

``````#include <iostream>
#include <string>
#include <cmath>

using namespace std;

int main()
{

bool	more	= true;
int		count	= 0;
double	sum		= 0;

float	num		= 0.0;
double	avg		= 0;
double	s_dev	= 0;

cout << " Enter a value: (CTRL-D to quit): ";

cin >> num;

while (true)

{

++count;
cout << count << endl;

sum += num;

cout << " Enter a value: (CTRL-D to quit): ";
cin >> num;

if  (cin.eof())
{
break;
}

}

avg = sum / count;

s_dev = sqrt((( pow(sum,2.0)) -(( 1.0/count) * (pow(sum,2.0)))) / (count - 1.0)
);

cout << endl << endl;

cout << " There are " << count << " values. " << endl;

cout << " The average is:  " << avg << endl;

cout << " The standard deviation is:  " << s_dev << endl;

return 0;

}``````

OK. So the tab didn't copy real well, but you get the idea.

You have a bug in your formula inputs.
To compute standard deviation, you must
accumulate the sum and the sum of the squares both.
Then compute the s.d. using the square-root of
the difference between the average of the squares and
the square of the average. It's simple, but you need