Arrays in functions C++
Sep 25, 2014 at 5:49am UTC
This code seems to only work while the array (dArray[]) is initialized with a set of given numbers instead of user inputs. This code is supposed to calculate:
*the Minimum
*the Maximum
*average
*root mean squared
*standard deviation
but seems that the numbers are off. Any help would be much appreciated, thanks.
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 79 80 81
#include <iostream>
#include <cmath>
using namespace std;
double GetMax(const double dArray[], int iSize) {
int iCurrMax = 0;
for (int i = 1; i < iSize; ++i) {
if (dArray[iCurrMax] > dArray[i]) {
iCurrMax = i;
}
}
return dArray[iCurrMax];
}
double GetMin(const double dArray[], int iSize) {
int iCurrMin = 0;
for (int i = 1; i < iSize; ++i) {
if (dArray[iCurrMin] < dArray[i]) {
iCurrMin = i;
}
}
return dArray[iCurrMin];
}
double GetAverage(const double dArray[], int iSize) {
double dSum = dArray[0];
for (int i = 1; i < iSize; ++i) {
dSum += dArray[i];
}
return dSum/iSize;
}
double GetRMS (const double dArray[], int iSize) {
double dSum = dArray[0];
for (int i = 1; i < iSize; ++i) {
dSum += dArray[i];
}
return sqrt(dSum/iSize);
}
double GetST(const double dArray[], int iSize) {
double mean= 0, sum_deviation=0;
int i;
for (i=0; i<iSize; ++i)
{
mean+=dArray[i];
}
mean = mean/iSize;
for (i=0; i<iSize; ++i)
sum_deviation +=(dArray[i]-mean)*(dArray[i]-mean);
return sqrt(sum_deviation/iSize);
}
int main()
{
double dValues[100];
int iArraySize;
int n, i;
cout << "Enter a number " << endl;
cin >> n;
cout << "Enter " << n << " number(s) followed by enter" << endl;
for (i=0; i<n; ++i){
cin >> dValues[n];
iArraySize = n;
}
cout << "Min = " << GetMax(dValues, iArraySize) << endl;
cout << "Max = " << GetMin(dValues, iArraySize) << endl;
cout << "Average = " << GetAverage(dValues, iArraySize) << endl;
cout << "Root mean squared = " << GetRMS(dValues, iArraySize) << endl;
cout << "Standard Deviation = " << GetST(dValues, iArraySize) << endl;
return 0;
}
Sep 25, 2014 at 6:22am UTC
See line 68. Notice any problems?
Sep 25, 2014 at 4:01pm UTC
Is it that I have to change n to a double?
Sep 25, 2014 at 4:10pm UTC
No. But it is a problem with what's between the brackets.
Sep 25, 2014 at 4:10pm UTC
Look closer, also look at the previous line, Think, what every varuable means and why is it in that particular place.
Sep 26, 2014 at 1:41am UTC
I figured it out, I had to change dValues[n] to dValues[i] and works now. Thanks for pointing out where the problem was. Simple mistakes.
Topic archived. No new replies allowed.