You are making several errors here. First of all, you never initialize the math[][] array to have values of 0, so while the dowhile loop exited after one execution, depending on what machine you run it on, you can run into problems. You are really a lot safer initializing the array so that all values are equal to 0. I think the behavior that you are experiencing on your machine is that since the array is uninitalized all values within it are assumed to be 0, and thus you will never have a case where you break from your while loop. Also, the reason that only 30ish numbers are being set as one is because even though you have 400 possible numbers that you can set (20*20), you are setting 40 numbers randomly, so there's a chance that your random number generator can give you repeat values. So that difference that you're seeing in between 40 and the number of 1's you have is the number of repeat values that you generate. This error should go away once you take care of initialization.
Also, there is a flaw in your logic. I'm thinking that you want to set 40 random 0's to 1's. With your current code, you will trigger an infinite loop in an actual initialized array. Thus you need to modify your setting algorithm slightly.
So, the lesson to learn here is that you never play around with any variables that you haven't initialized and ermmm, make sure that you really understand what do-while does.
May I suggest:
int math[20][20],aux2,aux3;
for(int i = 0; i < 20; i++)
{
for(int j = 0; i < 20; j++)
{
math[i][j] = 0;
}
}
for(int i=0;i<40;i++)
{
bool set = false;
while(!set)
{
aux2=int( rand()%20);
aux3=int( rand()%20);
if(math[aux2][aux3]==0)
{
math[aux2][aux3] = 1;
set = true;
}
}
}
int math[20][20],aux2,aux3;
for(int i = 0; i < 20; i++)
{
for(int j = 0; i < 20; j++)
{
math[i][j] = 0;
}
}
for(int i=0;i<40;i++)
{
bool set = false;
while(!set)
{
aux2=int( rand()%20);
aux3=int( rand()%20);
if(math[aux2][aux3]==0)
{
math[aux2][aux3] = 1;
set = true;
}
}
}
To copy to clipboard, switch view to plain text mode
Bookmarks