This is part of the question I met in the written test, which is recorded. For example, output any random number in [1,3].
1#include <iostream>2#include <cstdlib>3#include <cstdio>4#include <ctime>5 6 7 intMain ()8 {9 Srand ((unsigned) time (NULL));Ten One intval =0; A for(inti =0; I < -; i++) - { -val = (rand ()%3) +1; theStd::cout << i +1<<" "<< Val <<Std::endl; - } - return 0; -}
What does line nineth mean in the code?
In the C language, the rand () function can be used to generate random numbers, but this is not the true meaning of the random number, is a pseudo-random number, is based on a number, we can call it a seed, as a reference to a recursive formula derived from a coefficient, when the series of a large number of times, it is normal to publish, This is equivalent to generating a random number, but this is not a true random number, when the computer is properly booted, the value of this seed is fixed, unless you destroy the system, in order to change the value of this seed, C provides the Srand () function, its prototype is void Srand (int a)
1) First give Srand () a seed, it is a unsigned int type, its value range from 0~65535;
2) then call Rand (), which returns a random number (between 0 and 32767) based on the seed value provided to Srand ()
inductive : To obtain a random integer between [a, b], use (rand ()% (b-a)) + A or (rand () * (b-a))/Rand_max + A
REF:
http://blog.csdn.net/qin_zhangyongheng/article/details/8033936
Any random number in a range that allows a computer to be random in a C + + language