Rand (), srand () generates random numbers.

Source: Internet
Author: User
Tags random seed ranges

The rand () function can be used to generate random numbers, but this is not a real random number, it isPseudo-Random NumberIt is a coefficient derived from a recursive formula based on a number that we can call as a seed. When the number of series is large, it will conform to the normal announcement, this is equivalent to generating a random number, but this is not a real random number. When the computer starts up normally, the seed value is fixed unless you destroy the system, to change the value of this seed, C providesSrand ()FunctionThe original form is void srand (int ).
Initialize the initial values of the random generator rand () function, even if the seed value is changed to a. From this you can see that through the sand () function, we can generate predictable random sequences. How can we generate Unexpected random sequences? We may often need such a random sequence, right. ExploitationSrand (unsigned) Time (null ))Is a method, because every runProgramThe time is different.

Rand () returns a random value in the range0 to rand_max. Returns a random value between 0 and rand_max. rand_max is defined inStdlib. h(The value must be at least 32767). The result of the operation is an indefinite number. It depends on the variable type you define. The Int integer is 32767. Before calling this function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set, Rand () will automatically set the random number seed1. Generally, the for statement is used to set the number of seeds.

Currently, the C compiler provides an ANSI-based pseudo-random number generator function to generate random numbers. They areRand ()AndSrand ()Function.The two functions work as follows:

    • 1) First, provide a seed for srand (). It is of the unsigned int type and its value ranges from 0 ~ 65535;
    • 2) then call Rand (), which returns a random number (between 0 and 32767) based on the seed value provided to srand)
    • 3) call Rand () multiple times as needed to continuously obtain new random numbers;
    • 4) at any time, srand () can be provided with a new seed to further "randomize" the output results of rand.

Everyone may knowC LanguageBut the random function is not ansi c standard. Therefore, the random function cannot be compiled by GCC, Vc, or other compilers.

Random Number generated by random () is 0 or 1;

Random (n) generates a random number between 0 and N;

Rand () generates a random number between 0 and 32768.

First, use the random number "Seed" to initialize the srand function.Below is 0 ~ Random Number program between 32767

 1 # I nclude <stdlib. h> 2 # I nclude <stdio. h> 3 # I nclude <time. h>//  Use the current clock as the seed  4   5   Void Main ( Void  )  6   {  7      Int  I;  8 Srand (unsigned) Time (null )); //  Initialize Random Number  9   10     /*  Print 10 random numbers.  */  11        For (I = 0 ; I < 10 ; I ++ )  12 Printf ( "  % D \ n  "  , Rand ());  13 }
 
Example
 
/* Generate a random value ranging from 1 to 10. In this example, no random seed is set. For the complete random number generation, see srand ()*/
1 # Include <stdlib. h> 2   Int  Main ()  3   {  4       Int  I, J;  5       For (I = 0 ; I < 10 ; I ++ )  6   { 7 J = 1 + ( Int )( 10.0 * Rand ()/(rand_max + 1.0  ));  8 Printf ( "  % D  "  , J );  9   }  10       Return   0 ;  11   }  12   13   Execution result:  14   9   4   8   8   10   2   4   8   3   6   15  9   4   8   8   10   2   4   8   3   6  

According to the above program, it is easy to get 0 ~ Random number between 1:

 1 # Include <stdlib. h> 2 # Include <stdio. h> 3 # Include <time. h> 4   Int Main ()  5 { Int  I;  6   Srand (unsigned) Time (null ));  7          For (I = 0 ; I < 10 ; I ++ )  8 Printf ( "  % 5.2f \ n  " , Rand ()/32767.0  );  9       Return   0  ;  10 }

Generation 1 ~ The random number between 100 can be written as follows:

 1 # Include <stdlib. h> 2 # Include <stdio. h> 3 # Include <time. h> 4   Int  Main ()  5 {Int  I;  6   Srand (unsigned) Time (null ));  7          For (I = 0 ; I < 10 ; I ++ )  8 Printf ( "  % D \ n  " , Rand () % 100 + 1 );  9       Return   0  ;  10 }

Generate a random number between 0 and 99:

 1 # Include <stdlib. h> 2 # Include <stdio. h> 3   Int  Main ()  4   {  5      Int  I; 6 Printf ( "  Ten random numbers from 0 to 99 \ n  "  );  7      For (I = 0 ; I < 10 ; I ++ )  8 Printf ( "  % D \ n  " , Rand () % 100 );  9      Return   0  ;  10 }

 

How to generate a random number within the specified range

Since the random number generated by Rand ranges from 0 to rand_max, while rand_max is a large number, how can we generate a random number from X ~ What about the number of Y?

From X to Y, there is a number of Y-X + 1, so to generate the number from X to Y, you only need to write like this:

K = rand () % (Y-X + 1) + X;

In this way, you can generate random numbers in any range you want.

 

 

 

 

Here is the search:

 

Question 1: How to obtain a real random number? You know, Rand () cannot generate real random numbers! Even if you cannot generate a real random number, it should be close! And rand () is like every random.

 

Expert answers:

 

The reason why rand () has the same random number each time is that the rand () function is incorrectly used. VariousProgramming LanguageThe returned random number (pseudo-random number) is actually a set of values calculated based on the recursive formula. When the sequence is long enough, this set of values are approximately evenly distributed. If the initial values (called seeds) of the pseudo-random sequence are the same, the calculated pseudo-random sequence is exactly the same. This feature is used by software for encryption and decryption. During encryption, a pseudo-random sequence can be generated using the number of seeds for data processing. During decryption, a pseudo-random sequence is generated using the number of seeds and the encrypted data is restored. In this way, people who do not know the number of seeds need to spend more time to decrypt them. Of course, this completely identical sequence is very bad for you. To solve this problem, you must specify different seeds before each random sequence is generated, so that the calculated random sequence will not be identical. You can call srand (unsigned) Time (null) before calling the rand () function, so that the time function value (that is, the current time) is used as the number of seeds, because the time for calling the rand function twice is usually different, this ensures randomness. You can also use the srand function to specify the number of seeds. The Windows 9x/NT game freecell allows users to specify the number of seeds, so that if a game fails, the user can play again with the same licensing result next time.

Question 2: I cannot generate a random number according to the above method, and only generate an equality sequence with a tolerance of 3 or 4:

# Include <stdlib. h>

# Include <iostream. h>

# Include <conio. h>

# Include <time. h>

Void main ()

{

For (INT I = 0; I <100000; I ++)

{

Srand (unsigned) Time (null ));

Cout <rand () <Endl;

}

}

Expert answers:

Your program is faulty. Every time you call srand before a random number is generated, the computer runs very fast, so every time you use time, you get the same time (time precision is low, only 55 ms ). This is equivalent to using the same seed to generate a random sequence, so the random numbers generated are always the same. You should put srand out of the loop:

Srand (unsigned) Time (null ));

For (INT I = 0; I <100000; I ++)

{

// Related statements

}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.