Generation of random numbers in c ++ and c languages

Source: Internet
Author: User
Tags random seed

1: If a random number is generated without a set range, you only need to use rand (). rand () returns a random number with a range between RAND_MAX. RAND_MAX is defined in stdlib. h. Its value is 2147483647. example: # include <stdio. h> # include <stdlib. h> void main () {int I; for (int I = 0; I <10; I +) printf ("% d \ n", rand ());} (2) If you want to generate a random number in a certain range, you can define a random (int number) function in the macro definition, and then directly call random () in main () function: for example, randomly generate 10 0 ~ Number of 100: # include <stdio. h> # include <stdlib. h> # define random (x) (rand () % x) void main () {int x; for (x = 0; x <10; x ++) printf ("% d \ n", random (100);} (3) but the random numbers generated in the preceding two examples can only be one-time, if the output result is the same as that of the first running. This is related to the srand () function. Srand () is used to set the random number seed when rand () generates a random number. Before calling the rand () function to generate a random number, you must use srand () to set the random number seed. If no random number seed is set () during the call, the random seed is set to 1. In the above two examples, because no random number seed is set, each random number seed is automatically set to the same value of 1, which leads to the same random value produced by rand. Srand () function definition: void srand (unsigned int seed); generally, the return value of geypid () or time (0) can be used as seed. If you use time (0, header file # include <time. h> example: # include <stdio. h> # include <stdlib. h> # include <time. h> # define random (x) (rand () % x) void main () {int x; srand (int) time (0); for (x = 0; x <10; x ++) printf ("% d \ n", random (100 ));}

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.