C language rand () function usage, rand usage

Source: Internet
Author: User
Tags random seed

C language rand () function usage, rand usage

Rand () (Random Number Generation) related function srand () header file # include <stdlib. h> the int rand () (void) function indicates that rand () returns a random value ranging from 0 to RAND_MAX. 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 seed to 1. For details about random seed, see srand (). The Return Value Returns a random value between 0 and RAND_MAX. RAND_MAX is defined in stdlib. h and its value is 2147483647. Example/* generates a random number ranging from 1 to 10. In this example, no random seed is set. For the complete random number generation, see srand () */# include <stdlib. h> main () {int I, j; for (I = 0; I <10; I ++) {j = 1 + (int) (10.0 * rand () /(RAND_MAX + 1.0); printf ("% d", j );}} run the related function rand header file # include <stdlib. h> define the void srand (unsigned int seed) function. The function description srand () is used to set the random number seed when rand () generates a random number. The seed parameter must be an integer. Generally, the return value of geypid () or time (0) can be used as seed. If the same value is set for each seed, the random values generated by rand () are the same each time. The return value example/* generates a random number ranging from 1 to 10. This example and execution result can be referenced with rand () */# include <time. h> # include <stdlib. h> main () {int I, j; srand (int) time (0); for (I = 0; I <10; I ++) {j = 1 + (int) (10.0 * rand ()/(RAND_MAX + 1.0); printf ("% d", j );}} run 5 8 8 8 10 2 10 8 9 92 9 7 4 10 3 2 10 8 7

Related Article

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.