xxxxxxxxxx
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
/*Theory: time(NULL) returns the number of seconds since the
UNIX epoch (in the data type 'time_t' a fundamental C data
type). based on this ever-changing value, srand() generates
an initial seed for future rand() calls to produce random numbers*/
//rand() % n produces a random integer between 0(inclusive) <-> n-1(inclusive)
int num1 = rand()% 10; //range: 0 <-> 9
//rand() % (n-m+1) + m produces a random integer between m(inc.) <-> n(inc.)
int num2 = rand() % 8 + 13; //range: 13 <-> 20
}
xxxxxxxxxx
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define randnum(min, max) \
((rand() % (int)(((max) + 1) - (min))) + (min))
int main()
{
srand(time(NULL));
printf("%d\n", randnum(1, 70));
}
xxxxxxxxxx
#include <stdio.h>
#include <time.h>
int main(){
/*this is the seed that is created based on how much
time has passed since the start of unix time.
In this way the seed will always vary every time the program is opened*/
srand(time(NULL));
int max;
int min;
int n;
printf("give me the minimum number?\n");
scanf("%d", &min);
printf("give me the maximum number?\n");
scanf("%d", &max);
//algorithm to derive a random number
n = rand() % (max - min + 1) + min;
printf("random number:%d", n);
return 0;
}
xxxxxxxxxx
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
int card;
/* Do this only once at the start of your program,
otherwise your sequence of numbers (game) will
always be the same! */
srand(time(NULL));
/* Choose a number between 1 and 10 - we've called this 'card'
because the number represents a card from ace to a ten in this
program (rand() produces a large random int, we find the
remainder from diving by 10 using '%' mod operator, then add 1
so the card can't be 0) */
card = rand() % 10 + 1;
printf ("It's a %d.\n", card);
}
xxxxxxxxxx
//Note: Don't use rand() for security.
#include <time.h>
#include <stdlib.h>
srand(time(NULL)); // Initialization, should only be called once.
int r = rand(); // Returns a pseudo-random integer between 0 and RAND_MAX.