C language generates random numbers

Source: Internet
Author: User

Rand () function
#include <stdlib.h>int rand(void);

Rand () is a function that calculates a series of numbers based on a seed, with a particular algorithm. The number returned is between 0 and Rand_max. Rand_max is defined in stdlib.h, at least 32767.

However, this generates pseudo-random numbers because the seeds are set up after the computer is turned on, so this series of numbers are predictable and each time the sequence is equal. To get a real random number, you have to reset the seed.

Srand () function
#include <stdlib.h>void srand(unsigned int seed);

Srand (seed) is a function of the C language that sets the seed of a random number, usually using time as seed, and each time it runs differently, so the resulting random number seed is also different. Srand (Time (NULL))

How to generate random numbers
    1. Call Srand (Time (NULL)), set the random number seed
    2. Call Rand () repeatedly to generate a random number
#include <stdlib.h>#include <stdio.h>#include <time.h>            void main( void ){  int i;  srand((unsigned)time(NULL));              for(i = 0; i < 10; i++) {                                  printf("%d\n", rand());    }}

C language generates random numbers

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.