+ 1

What is the coding of rand () function

7th Jul 2016, 5:30 PM
VARUN MALIK
VARUN MALIK - avatar
2 Respuestas
0
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main () { srand(time(NULL)); int x = (rand ()%43)+1; cout <<x; return 0; }
7th Jul 2016, 8:58 PM
destro
0
I think Varun meant how the rand() function is defined. Therefore I will answer this interpretation of his question. I cannot give you the specific implementation of the rand function as in the standard library. Nevertheless, I will give you some hints of how it is done in a very simple way. The simplest random number generators I've come to know are "Linear Congruential Generators" (LCGs). If you want more info on.them, there's, of course, a Wikipedia article about it: https://en.m.wikipedia.org/wiki/Linear_congruential_generator :-) LCGs in simple C++ are of the form: int valueBefore = 0; // Something you can define const int C1 = 11; // Something you can define const int C2,= 11; // Something you can define void seed (int seed) { initialValue = seed; } int rand() { newValue = (valueBefore + C1) % C2; valueBefore = newValue; return newValue; } This could be the implementation of the rand() function. There are other random number generators available in libraries like Boost.
8th Jul 2016, 8:48 PM
Stefan
Stefan - avatar