Click to See Complete Forum and Search --> : random number
metalguy
May 18th, 2002, 07:44 PM
how would you generate a random number between 1 and 52? including 1 and 52
abdul
May 18th, 2002, 08:24 PM
Try
int mynum = rand()%1+52;
or
int mynum = rand()% 53;
if it doesn't include 1 and 52;
aicungbiet
May 23rd, 2002, 01:05 AM
Try: (rand() % 52) + 1
DaoK
May 23rd, 2002, 10:15 AM
why you use "%" and not "*" ?
In VisualBasic or in Java we never use modulo for random operation ?
parksie
May 23rd, 2002, 01:15 PM
int num = int((float(rand()) / RAND_MAX) * 52.0) + 1;% isn't valid for floating-point numbers...
DaoK
May 23rd, 2002, 05:18 PM
anyone can tell me what rand() return ? I have done some test and i return about 3 to 6 decimal number ? why isn't between 0 and 1 like VB or Java?
I do not understand why we use MOD (%) ? Anyone can tell me a mathematic answer about that ?
parksie
May 23rd, 2002, 05:27 PM
You shouldn't need modulus...
rand() returns a number between 0 and RAND_MAX. So, to get it between 0 and 1, divide rand() by RAND_MAX. Then just multiply by 52.
I can't see where % would come into it.
CornedBee
May 24th, 2002, 10:27 AM
It's very simple. Most random functions return a flloating point number between 0 and 1. CRT rand() returns an integer between 0 and RAND_MAX (which is defined as 32767, the highest positive integer possible for a 16 bit signed variable). To get a number between 0 and n (exclusive), simply do
rand() % n;
which puts all numbers in this area. It might not be completly fair (the lowest numbers have a slightly higher probability), but it is fast.
A slightly more fair approach is parksie's snippet, but it is considerably slower, having one FDIV, one FMUL, two int-to-float conversions (one on good compilers), one ADD and one float-to-int conversion as opposed to on DIV of the first approach (386 DIV instruction computes division and modulo at the same time).
So, if you don't need any special accuracy, use %. Else, use the floating thing or wait for quantum computers, which can produce real random numbers.
parksie
May 24th, 2002, 11:28 AM
Originally posted by CornedBee
So, if you don't need any special accuracy, use %. Else, use the floating thing or wait for quantum computers, which can produce real random numbers. Or give a number to your users and tell them to multiply it by two and enter it in again. Chances are, none of them will ever give the same number :D
CornedBee
May 27th, 2002, 07:40 AM
:D
Unless you're stuck with people who mindlessly follow any instructions the program gives them. :rolleyes:
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.