C and pointer notes-make Rand more random

Source: Internet
Author: User

In C, If You Want To obtain 1 ~ A random number of 10, so most people may think of it through the following code:

Rand () % 10 + 1;

(Although Rand generates a pseudo-random number, I think it is really random here)

But generate 1 ~ Is the probability of 10 the same?

No. Let's analyze the following.

If the maximum value returned by Rand is 105, then the random number obtained using the method above generates 1 ~ 6 is more likely than generating 7 ~ The probability of 10 is high,

See it? Because if the returned value range of the rand function is 0 ~ 99, use the above method to generate 1 ~ The probability of 10 is the same,,

The returned value range of Rand is 0 ~ 105. If Rand returns 100, the value of rand () % 10 + 1 is 1, which indicates that the probability of 1 is greater than that of other numbers,

Generate 1 ~ 6 is a little more likely.

So if you want to make the generated number more random, you can use the following code:

# Include <stdlib. h> # include <stdio. h> int get_rand10 (void) {int value; int max_rand = (rand_max + 1)/10) * 10-1; srand (unsigned INT) Time (null )); do {value = rand ();} while (value> max_rand); Return Value % 10 + 1 ;}

In general, you do not need to use the above method, but the maximum value of the random number to be generated is closer to rand_max, and the above method should be considered.

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.