I want to generate a random number to apply to some arrays in order to get different elements in each execution. The arrays contain names of sport products (product,size,price,etc). By doing this, I want to make random products that would go into a String, but in each execution of the program, I get the same product.
Where is the problem?
Here is the code in the class generaProductos:
public void generaProductos() {
int num;
for (int i=0;i<3;i++){
num = (int) Math.random() * 3;
String cliente = tipoProducto[num] + " " + deporte[num] + " " +
destinatario[num] + " " + color[num] + " " + tallaRopaAdulto[num]
+ " " + preciosIVA[num];
System.out.println(cliente);
}
return;
}
And here is where I call generaProductos()
method in main:
switch (opt){
case 1:
generaProductos alm = new generaProductos();
alm.generaProductos();
When I execute my code, I always receive this:
Botas Futbol Hombre Marron S 16.99
Botas Futbol Hombre Marron S 16.99
Botas Futbol Hombre Marron S 16.99
(In English it would be Football boots men brown size S 16.99)
The rand() function in C++ is used to generate random numbers; it will generate the same number every time we run the program. In order to seed the rand() function, srand(unsigned int seed) is used.
This is because MATLAB's random number generator is initialized to the same state each time MATLAB starts up. If you wish to generate different random values in each MATLAB session, you can use the system clock to initialize the random number generator once at the beginning of each MATLAB session.
The reason is that a random number generated from the rand() function isn't actually random. It simply is a transformation.
You cast a floating point value between 0 and 1 (exclusive) to int
, which results in 0, and then multiply 0 by 3, which is still 0.
change
(int) Math.random() * 3
to
(int) (Math.random() * 3)
num = (int) Math.random() * 3;
will always be 0
, because of order of precedence.
Math.random()
is always < 1
so casting it to int
will give you 0, then you multiply, still getting 0.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With