How to get a random number?

Hey, I've made a genetic algorithm program that's not generating very random numbers. Every time I run it, it generates the same ten million or so random numbers. The -exact- same set of ten million "random" numbers.

I'm using rand() bit with one srand( (unsigned)time(NULL) ) at the start of the program. The numbers look fairly random, and they're all different, it's just that I get the same set over and over even when I restart the program.

Is there an easy fix to this one? If not, I may just end up rewriting the code in MatLab to side-step the issue.
Try this:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
  srand(time(NULL));

  for(int i=0;i<10;i++)
      cout <<rand()<<endl;
      
  return 0;
};

If this code generates different numbers every time you run it, then the problem is somewhere in your code.
more suitable for C++

srand(static_cast<unsigned>(time(0)));
Problem is in line 11..

You should have a function for random number
It will look something like that:

int random_integer(int min,int max)
{int random_integer;
random_integer = rand()%(max-min)+1;}

then inside program you can write for loop for as many numbers as u want to output

for (int i=0;i<n;i++) // n -number of random numbers you want
{random_integer(1,10);
cout<<endl<<random_integer;}
-------------------------------------------
Your thing will look like this:

#include <iostream>
#include <ctime>


using namespace std;

int random_integer(int min,int max)
{int random_integer;
random_integer = rand()%(max-min)+min;}

main()
{
int n,r;
srand(time(0));
cout<<"How Many Random Numbers?";
cin>>n;

for (int i=0;i<n;i++) // n -number of random numbers you want
{
r=random_integer(1,10);
cout<<endl<<r;}

cin>>n;
}

each time you'll have different set of numbers
Topic archived. No new replies allowed.