How to generate random numbers in C language

Source: Internet
Author: User
Tags rand

The simple code that generates 0~100 random numbers is as follows:

#include <stdio.h>
#include <time.h>

void Main ()
{
    int i=0,j=0;
    int p;

    Srand (NULL),//Generation time seed
    P=rand ()%100+1;//generate random number
    printf ("%d\t", p);
    printf ("\ n");
}

in the above code we can see that three functions are used, namely srand,rand and time functions.

The function of Srand () is to provide a seed whose function format is void srand (unsigned int seed). Seed here we call it the time seed, and if it is not srand, the time seed does not change, thus the random number produced by Rand () never changes.

Then call Rand () with the format int rand (void). It returns a random number (between 0 and 32767) based on the seed value provided to Srand (), and we can vary the range by operation according to our own needs.

The time () function is to produce a positive integer, which is the number of seconds elapsed since 00:00:00 January 1, 1970. Here we have to worry about the size of a positive integer, in fact, is more. The limit of the INT type variable 2147483647 is the time of 2038-01-19 11:14:7. So we don't have to worry about that. And now the time_t structure is signed int 32, or 32 bits. This problem can be solved with the upgrade to 64 digits.

About the Time.h header file will be introduced in the next blog post.

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.