FAQ Randomize?????? (C++) [Archive] - C Board

PDA

View Full Version : FAQ Randomize?????? (C++)


Stealth
10-03-2001, 12:39 AM
Hello


I was wondering


how do I randomize a value, I need this to decide random outcomes (obviously) thanks for any help simple code will do me

cheers

stealth

LlamaDolittle
10-03-2001, 01:46 AM
You can use the rand() function in cstdlib to get a random number.

It is used like this:


int x = rand() % 5; //x would be between 0 and 4

Before calling rand(), you should call srand() to seed the random number generator. You must always use a different number when calling srand(), the current time for instance, or else rand() will always give you the same numbers.

So you might want to do something like this:


#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int RandInt(int a,int b)
{
return a + rand() % (b - a + 1);
}

void main()
{
//Seed rand() with current time
srand(unsigned(time(NULL)));
//x will be between 2 and 10, inclusive
int x = RandInt(2,10);
cout<<x;
}

kitten
10-03-2001, 03:32 AM
There is more information of randomizing in the FAQ.

Stealth
10-03-2001, 05:47 AM
ok thanks for the help guys

cheers

stealth

Unregistered
10-09-2001, 09:33 AM
I've tried doing random numbers using that same method and wanted to do random numbers between 1 and 100.

here are my results
2, 9,12,19,24, ..... etc, etc you get the idea I guess. There always increasing. Not really random. Is there anyway to get around this?

HelloWorld
10-09-2001, 08:41 PM
Yea there is you could do this


random{int n ) {


static bool seeded = false; /* used to ensure seeding done just one */

int seed;


if(!seeded) {

cout <<"Enter a value to randomize a value" << endl;
cin>> seed;
cin.ignore(80,'\n');
srand(seed);
seeded = true;
}

* then you call your rand() */

Rick
11-05-2001, 01:35 PM
cout <<"Enter a value to randomize a value" << endl;
cin>> seed;
cin.ignore(80,'\n');
srand(seed);
seeded = true;

don't work in a visual C++ Dialog window or what ever you want ever there called. And I don't really want to have to enter a value every time I run it. Is there anyother way to do what I want?

LlamaDolittle
11-05-2001, 08:36 PM
If you want different seeds everytime you could use the current time. So you would do something like this:

#include <time.h>

srand(unsigned(time(NULL)));

Then you will get different numbers from rand() every time without having to specify a seed value.