random numbers

M

moni

Hi,

Can anyone tell me , how I would generate random numbers, for an
interval say from 15 to 450 in C.

Plz lemme know.

thanx..
 
J

JohnGoogle

I just tried this example:

class TestRandom
{
static void Main(string[] args)
{
Console.WriteLine("Testing Random class");

Random rand = new Random();

for (int i = 0; i < 100; i++)
Console.WriteLine("Value {0}",rand.Next(15,451));

Console.WriteLine("\nPress ENTER to close");
Console.ReadLine();
}
}

Random.Next expects a min and max value as parameters. Min is inclusive
and max is exclusive (that's why I passed 15 and 451).

Hope this helps.

BTW. I found this (didn't know it before hand) by searching for random
is the object browser. I find it exteremly useful when trying to find
things that I don't know about.

John.
 
M

Michael Goldfarb

The standard C functions do not have arguments for a range of values.
You can however easily create a function to do this:

int myRand(int min, int max)
{
srand(time(0));
return (rand()%(max-min))+min;
}
 
J

JohnGoogle

Sorry.

As it was a csharp newsgroup I thought the OP was wanting to know how
to do it in C# / .NET. I now see that he said C.
 
B

bwray314

Michael said:
The standard C functions do not have arguments for a range of values.
You can however easily create a function to do this:

int myRand(int min, int max)
{
srand(time(0));
return (rand()%(max-min))+min;
}

To the OP:

This works, but don't do copy/paste this into your code. In your code,
be sure to call srand(time(0)) somewhere else (top of main() is good)
or every single call to myRand() in the same clock second will return
the same random number.

And in case you weren't already aware, you'll also need to #include
<time.h> and <stdlib.h> to have the time(), rand(), and srand()
functions prototyped.
 
M

moni

Thanx alot. I did that, and am getting random numbers,
But is there a way by which I can get unique numbers?

Thanks.
 
R

Rick Lones

moni said:
Thanx alot. I did that, and am getting random numbers,
But is there a way by which I can get unique numbers?

Thanks.

Depends what you mean. If the generation is really random (or pseudo-random)
there is no guarantee that the generated sequence would contain unique numbers.
Is what you really want a random permutation (shuffle) of the integers from 15
to 450?

-rick-
 
R

rossum

Thanx alot. I did that, and am getting random numbers,
But is there a way by which I can get unique numbers?

Thanks.

Knuth, Volume II, Algorithm 3.4.2 P

rossum
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top