How does VC ++ generate real random numbers?

Source: Internet
Author: User

How do I write a program to make it run at different random numbers? See the following example:
# I nclude <stdlib. h>
# I nclude <stdio. h>
# I nclude <time. h>
# I nclude <iostream>
Using namespace STD;
Int main (void)
{
Int I;
Time_t t; // based on the time of the computer, the minimum value is 55 ms.
Srand (unsigned) Time (& T ));
Cout <"ten random numbers from 0 to 99 \ n ";
For (I = 0; I <10; I ++)
Printf ("% d \ n", Rand () %100 );
Return 0;
}
When you run the program, you will find that the random numbers generated each time are different.
The program uses a new function srand.
This function generates a random seed for a random number. The prototype of the function is srand (unsigned) Time (null ));
The value of time varies every moment. So the seeds are different, so the random numbers are also different.
Therefore, to generate different random numbers, you must call srand before using Rand.
Both the srand and Rand functions are included in the header file of stdlib. h. The time function is included in time. h.
Since the random numbers produced by Rand are from 0 to rand_max, while rand_max (32767) 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;

Example 1 ~ 255. K = rand () % 244 + 1;
In this way, you can generate random numbers in any range you want.

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.