the problem is the following I have my code in which 10 random numbers are generated in an array, then it shows them and then it orders them, what I want is that when re-executing the "fill" function, which is the one that generates the numbers an array is generated with new numbers and they are not the same as the previous time.
#include<iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int llenar();
int mostrar();
int array[10];
int burbuja();
int main(){
llenar();
mostrar();
burbuja();
llenar();
mostrar();
};
int burbuja(){
int i,j,aux;
for(i=0;i<10;i++){
for(j=0;j<10;j++){
if(array[j] > array[j+1]){
aux = array[j];
array[j] = array[j+1];
array[j+1] = aux;
}
}
}
for(i=1;i<11;i++){
cout<<array[i]<<" ";
}
cout<<endl;
}
int mostrar(){
for(int i=0; i<10; i++){
cout << array[i] << " ";
}
cout<<endl;
};
int llenar(){
array[0]='NULL';
int num, c;
srand(time_t());
for(c = 1; c <= 10; c++)
{
array[c-1] = 1 + rand() % (100 - 1);
/* cout << array[c-1]<< " ";*/
}
return 0;
}
You have a few bugs :
If it is
int array[10]
, surely what you want to do isChanging the above, and also
srand( time( NULL ) );
, the numbers start to come out random.Apart from that, you declare
Y
However, in none of them do you return anything , and the compiler warns you.
And the last:
You have another notice that you don't use the variable
num
.edit
It repeats the numbers because, between successive calls to
srand( time( NULL ) )
, too little time passes .To make the effect more noticeable, remove it
srand( )
from the functionllenar( )
and put it at the beginning ofmain( )
If you want " C++ Random Number Generator " completely forget about C utilities like C
rand
headers<stdlib.h>
and<time.h>
.Starting from the C++11 standard, the C++ language offers a complete pseudo-random number generation library that allows you to choose the probability distribution (uniform, Bernoulli, Poisson, normal, discrete, constant, linear...), the underlying type of the generated value and even the algorithm to use (minstd, mt19937, ranlux, knuth...).
From your question I deduce that you want a uniform distribution (which is what
rand()
1 offers ) between 1 and 100. With the C++ pseudo-random number library it can be done like this:Each time it is called
llenar
, a new one will be createdstd::random_device
which will have a different seed and consequently give different numbers.1 But its uniformity is destroyed by using the modulo operation, as it is in your code.
Try including the ctime library :
And then in the fill function , change:
By:
The srand function defines a seed that changes the pseudorandom sequence that rand generates . Using time(NULL) the current value of time is used as a seed, which will make the sequence generated by rand different each time the program is executed . Your code is already doing this, but (without testing) I think this way should work.