Calculating standard deviation of 3 numbers

Okay so I've written the code to calculate standard deviation of 3 numbers and I don't know what's going wrong here... :s
I have to use these three functions to do the task they are doing right now..
Also, I don't know how to use summation in c++, and that's why I'm calculating std deviation like this... here's the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <cmath>
using namespace std;
double mean3(double n1, double n2, double n3);
double stdev3(double n1, double n2, double n3);
int main ()
{
	double n1, n2, n3;
	cout << "Enter three numbers: ";
	cin >> n1 >> n2 >> n3;
	stdev3(n1, n2, n3);
	cout << stdev3(n1, n2, n3);
	return 0;
}
double stdev3(double n1, double n2, double n3)
{
	mean3(n1, n2, n3);
	double sd = sqrt((1/3)*(pow((n1 - mean3(n1, n2, n3)),2)+pow((n2 - mean3(n1, n2, n3)),2)+pow((n3 - mean3(n1, n2, n3)),2)));
	return sd;
}
double mean3(double n1, double n2, double n3)
{
	double mean = (n1+n2+n3)/3;
	return mean;
}


The program is returning 0 for any values i enter.. :/
Please tell me what I'm doing wrong? :S
Thanks!
P.S. I've just started using c++ so please don't use much technical language.. :P
Last edited on
I think it is the
1
2
3
double sd = sqrt((1/3)* ....
// Change it to 
double sd = sqrt((1.0/3.0)*

Thanks a lot histrungalot! :D that worked like a charm... such a small detail phew!
thanks a lot again..
Though I'd like to know how to use the summation thing instead of

double sd = sqrt((1/3)*(pow((n1 - mean3(n1, n2, n3)),2)+pow((n2 - mean3(n1, n2, n3)),2)+pow((n3 - mean3(n1, n2, n3)),2)));

:s
You would have to test it a little more and add some error checking but it could go like this.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include <vector>
#include <iostream>
#include <sstream>
#include <cmath>
using namespace std;
double meanVec(vector<double> &);
double stdevVec(vector<double> &);
int main ()
{
   istringstream inStrm;
   vector<double> numVec;
   double n;
   string nums;    
   cout << "Enter numbers: ";
   getline(cin, nums);
   inStrm.str(nums);
   while (inStrm >> n ) {
      numVec.push_back(n);
   }
   cout << stdevVec(numVec) << endl;
   return 0;
}
double stdevVec(vector<double> &nums)
{
   double m(meanVec(nums)),sum(0);
   for (int i(0); i<nums.size();i++)
     sum += pow(nums[i]-m,2); 
   return sqrt(sum/double(nums.size()));
}
double meanVec(vector<double> &nums)
{
   double mean(0); 
   for (int i(0); i<nums.size();i++)
       mean += nums[i];
   return mean/double(nums.size());
}
$ ./a.out
Enter numbers: 1 2 3 4 5 6 7 8 9 10
2.87228
$
Last edited on
Topic archived. No new replies allowed.