Oct 23, 2013 at 9:31am UTC
Hi.
I have written a code to calculate standard deviation. The program runs fine, but it does not give the correct outcome.
For my numberOfentries I used 4 and then 1.0 5.0 -1.4 3.9.
Can anyone spot the problem, I have been looking at it for a while now and can´t figure it out.
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 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
#include <iostream>
#include <cmath>
using namespace std;
//void output (double x[] , int staerd);
void read_numbers (double x [] , int staerd);
double deviation (double x[] , int staerd );
double medaltal (double x[] , int staerd);
int main()
{
int numberOfentries = 0;
cout << "Enter how many numbers you want to enter: " ;
cin >> numberOfentries;
const int staerd = numberOfentries;
double x [staerd];
read_numbers(x , staerd);
deviation(x , staerd);
cout <<"deviation is" << deviation (x , staerd);
return 0;
}
void read_numbers (double x [], int staerd)
{
for (int i = 0; i < staerd ; i ++ )
{
cin >> x[i];
}
for (int i = 0; i < staerd ; i ++ ) // debugger til að sjá hvort tölurnar fóru rétt inn
{ cout << x[i] << " " << endl; }
return ;
}
double medaltal (double x[] , int staerd)
{
double sum = 0;
double medalt = 0;
for (int i = 0; i < staerd; i++)
{
sum += x[i];
}
medalt = sum / 4;
return medalt;
}
/
double deviation (double x[], int staerd )
{
double deviation;
double sum2 = 0;
double medaltal2 = medaltal(x , staerd);
for ( int i = 0; i < staerd; i++ )
{
sum2 += pow((x[i]- medaltal2), 2);
}
deviation = sqrt(sum2 / (staerd-1));
return deviation ;
}
Last edited on Oct 23, 2013 at 11:22am UTC
Oct 23, 2013 at 4:00pm UTC
For starters you can't declare your array on line 19 like that the array size must be known at compile time.... unless
You want to do something like
double *x = new double [staerd];
just remember to delete what you made new before exiting your main
delete [] x;
There are a few other things to look at but you should be able to get a good start from here.
Last edited on Oct 23, 2013 at 4:02pm UTC
Oct 23, 2013 at 9:21pm UTC
Hi,
thanks for your reply.
I found out the problem and resolved it.
1 2 3 4
cin >> numberOfentries;
const int staerd = numberOfentries;
double x [staerd];
I am getting the size here from the user.
and there was a number in my deviation calc that was messing up.
Last edited on Oct 23, 2013 at 9:22pm UTC