• Support PF! Buy your school textbooks, materials and every day products Here!

Standard Deviation C++ Program

  • Comp Sci
  • Thread starter Mindscrape
  • Start date
  • #1
1,860
0
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?
 

Answers and Replies

  • #2
1,356
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
1,860
0
I think I see what you are getting at. The data declaration should be below where the number of elements is read?
 
  • #4
1,997
5
Think about this: how would the compiler know how big to make the array?
 
  • #5
1,860
0
So I could either make a pointer or just move the declaration.

Awesome, thanks.
 

Related Threads on Standard Deviation C++ Program

Replies
1
Views
3K
  • Last Post
Replies
1
Views
4K
  • Last Post
Replies
1
Views
2K
Replies
3
Views
7K
Replies
5
Views
767
  • Last Post
Replies
4
Views
4K
  • Last Post
Replies
0
Views
843
  • Last Post
Replies
1
Views
2K
  • Last Post
Replies
9
Views
2K
Top