Di Posting Oleh : Simple Learning
Kategori : rand() random number examples srand() time()
This tutorial contains
Computers actually cannot generate truly random numbers because they are not human. Computer follows some algorithms to generate random numbers to make it more random.
rand() with srand() function
rand() function is a function in header file stdlib.h which simply returns a random number.
srand();
prototype: void srand(unsigned int seed);Return type: void
Takes an unsigned int argument as seed for example srand(10); which simply changes the algorithm
Lets discuss it with code examples
srand(); will just change the algorithm if we run the program again and again it will generate the same random number with a same pattern
like below program
it generates 1,9,2,4,7 again and again
lets change the code with a for loop srand(i);
after running it again and again it is also generating a sequence again and again
like 1,5,8,1,4
now lets use srand(); two times in a program and see what happened
sample output
41
45
so change the value of srand() changing the random number.
time() function c++ code
- rand(); srand() and time() concept and how to use these functions
- srand() example with rand() with in a for loop
- rand() srand() and time program code with for loop
Computers actually cannot generate truly random numbers because they are not human. Computer follows some algorithms to generate random numbers to make it more random.
rand() with srand() function
rand() function is a function in header file stdlib.h which simply returns a random number.
srand();
prototype: void srand(unsigned int seed);Return type: void
Takes an unsigned int argument as seed for example srand(10); which simply changes the algorithm
Lets discuss it with code examples
srand(); will just change the algorithm if we run the program again and again it will generate the same random number with a same pattern
like below program
#include<iostream> |
it generates 1,9,2,4,7 again and again
lets change the code with a for loop srand(i);
#include<iostream> |
after running it again and again it is also generating a sequence again and again
like 1,5,8,1,4
now lets use srand(); two times in a program and see what happened
#include<iostream> |
sample output
41
45
so change the value of srand() changing the random number.
time() function
- This functime comes from a header file which is <ctime.h>
- It simply allows us to get the system or computers current time in seconds
- Its is very use full function with srand() we will call it within srand() and will get different random number every time because seconds value is changing
time() function c++ code
#include<iostream> |
0 Response to "How to use rand, srand and time function cpp"
Post a Comment