Hello guys, I was given an assignment by my prof to code statistical calculation which are average, variance, and standard deviation. Some says it is easier to use pointer but to this date, my prof only covered up to array. I'm a total beginner to begin with. My output of this code should be:
How many numbers do you wish to enter? 5
Enter 5 numbers:
3 4 2 1 7
The average is 3.4
The variance is 5.3
The standard deviation is 2.30217
or
How many numbers do you wish to enter? 6
Enter 6 numbers:
1
10.4
-6.2
5.55
0.03
-17
The average is -1.03667
The variance is 92.1911
The standard deviation is 9.60162
This is my code as far and they give to many errors. Please clarify what I'm doing wrong.
You aren't too far off, just remove the '+i' in line 23 rewrite line 24 as
sum += a[i]
and the program should be fine. A few general points otherwise:
- variable value is unused and should be removed if so
- why do you need variables n and num
- you may also wish to give your vector a more memorable name just as you've done for the other variables
- I haven't double-checked the variance formula, assume that wasn't the problem
- since you've been introduced to iomanip you may also wish to round off the results to 2 or 3 decimal places
#include<vector> is the header file required when you work with vectors, if you'd used the array instead as in the OP you wouldn't need it. The change would be instead of vector<double> a(n) it'd be double a[n] just as you had previously
If I just want to use cmath and iostream, how can I change my code to give the asked ouput?
There are at least two approaches:
1. Use a "large enough" static array:
1 2 3 4 5 6 7 8 9 10 11 12
constint MaxN = 42; // something reasonably big
double a[MaxN];
int n;
std::cin > n; // get user's choice
if ( MaxN < n ) {
// Our array is too small. We can either
// quit program: return 1;
// or
// use less than user wants: n = MaxN;
// either way: tell to the user about the problem
}
2. Manage dynamic memory manually:
1 2 3 4 5 6 7 8 9 10 11
int n;
std::cin > n; // get user's choice
if ( n < 1 ) {
// handle this error;
}
double * a = newdouble [n]; // dynamic memory allocation
// use a
delete [] a; // deallocation. Must be done properly
The deallocation can be non-trivial in complex branched code. To make it more automatic, the standard library offers smart pointers, for example std::unique_ptr.