how would you generate a random number between 1 and 52? including 1 and 52
Printable View
how would you generate a random number between 1 and 52? including 1 and 52
Try
orPHP Code:int mynum = rand()%1+52;
if it doesn't include 1 and 52;PHP Code:int mynum = rand()% 53;
Try: (rand() % 52) + 1
why you use "%" and not "*" ?
In VisualBasic or in Java we never use modulo for random operation ?
% isn't valid for floating-point numbers...Code:int num = int((float(rand()) / RAND_MAX) * 52.0) + 1;
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 ?
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.
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.
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 :DQuote:
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.
:D
Unless you're stuck with people who mindlessly follow any instructions the program gives them. :rolleyes: