### a little function

hi all.
i wrote this

int crea_vett ( int vett[], int size )

{
int indice;
int poss[9] = {1, 2, 3, 4, 5, 6, 7, 8, 9};

srand( time( NULL ));

for ( int i = 0 ; i < size ; i++ ) {
indice = rand()%9 + 1;
while ( poss[indice] == 0 )
indice = rand()%9 + 1;
vett[i] = poss[indice];
poss[indice] = 0;
}
return 0;
}

a little function for the creation of a 4 different elements array. the elements have value from 1 to 9 and are chosen by the function rand().

that's the problem: running it, sometime i obtain value like 1330021354561 for an element!!
where's my error?? =(
Indice can be 9, but the valid element ranges are 0-8 (9 different elements). Use indicde = rand()%9; instead of +1.
Would you please save our time by putting the entire code. And why your function like that. it is messed up.

 ``1234567891011121314151617181920212223`` ``````#include #include #include int const SIZE = 4; void crea_vett(int vett[], const int& size ) { srand( (unsigned int)time( NULL )); for ( int i = 0 ; i < size ; i++ ) { vett[i] = rand()%9 + 1; std::cout << vett[i] << std::endl; } } int main() { int vett[SIZE] = {0}; crea_vett(vett, SIZE); std::cin.get(); return 0; }``````
Last edited on
This code is wrong

indice = rand()%9 + 1;
while ( poss[indice] == 0 )
indice = rand()%9 + 1;
vett[i] = poss[indice];

If an array has N elements its indexes are in the range [0, N-1]

You are genereating indexes in the range [1, 9] for an array that has 9 elements.
Topic archived. No new replies allowed.