Random numbers srand

1

It consists in drawing two numbers at random, but surely you have to reinitialize the srand because it goes wrong and in another project that I have the two numbers are the same.

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main()
{
  int numero,numero2;
  srand(time(NULL));
  numero=rand() % 5+1;

  cout << "El numero es:"<<numero<<endl;

  srand(time(NULL));
  numero=rand() % 5+1;

  cout << "El segundo numero es:"<<numero2;

}
    
asked by Vendetta 28.10.2017 в 13:06
source

2 answers

3

Srand () , is only initialized once in the program that you execute , so it starts running with the variable or function that you passed, in this case < strong> time (NULL) . Then, to generate several numbers, you have to save each one in a different variable, this being the best way.

#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;

int main(){
   int numero,numero2;
   srand(time(NULL));
   numero=rand()%5+1;
   numero2=rand()%5+1;
   cout<<"El primer numero es:"<<numero<<endl;
   cout<<"El segundo numero es:"<<numero2<<endl;
}
    
answered by 28.10.2017 / 18:21
source
2

The problem in the program is not with rand() but in the variables used. In the second call to rand() you do the following:

numero=rand() % 5+1;

It was probably a copy-paste error. I think your intention is to do the following:

numero2=rand() % 5+1;

Try to use more descriptive variable names so that you avoid this situation and the program is more readable.

    
answered by 28.10.2017 в 17:28