Standard Deviation C++ Program

  • #1
1,861
1
I wrote a program that is supposed to find the standard deviation of a set, but something really strange happens in a for loop that I have in my main function.

int main()
{
int i=1;
int NUMBER_OF_ELEMENTS;
double data[NUMBER_OF_ELEMENTS];

cout << "Please enter the number of elements followed by each individual data element:" << endl;
cin >> NUMBER_OF_ELEMENTS;

for(i=1;i<=NUMBER_OF_ELEMENTS;i++)
{
cout << "Data element " << i << ": ";
cin >> data[i-1];
cout << endl;
}


cout << "The standard deviation is: " << std_dev(data, NUMBER_OF_ELEMENTS);
return EXIT_SUCCESS;
}

No matter what size I give to the array (for the number_of_elements), the integer, 'i,' in the for loop will go to 2, and the next time through the loop 'i' increments to some wacky number (i.e. 1432104).

Can anyone pick out what would cause something strange like this?
 
  • #2
what compiler did you use to? does it actually compile?
do you know anything about "static vs dynamic allocation"?
and what do you expect these two lines to do:

int NUMBER_OF_ELEMENTS;
double data[NUMBER_OF_ELEMENTS];
 
  • #3
I think I see what you are getting at. The data declaration should be below where the number of elements is read?
 
  • #4
Think about this: how would the compiler know how big to make the array?
 
  • #5
So I could either make a pointer or just move the declaration.

Awesome, thanks.
 

Suggested for: Standard Deviation C++ Program

Replies
2
Views
649
Replies
1
Views
350
Replies
8
Views
589
Replies
8
Views
738
Replies
2
Views
529
Replies
2
Views
847
Replies
8
Views
553
Replies
3
Views
505
Replies
1
Views
352
Back
Top