C++:c++ generates random numbers outside a particular area of the picture __c++

Source: Internet
Author: User
Tags rand random seed

Reference text: C + + produces random number (integer)

C + + in a specific area of the picture generated random numbers, avoid regular expressions, can be divided into two situations.

First: Generate random numbers before a certain number; the second, generate random numbers, plus a certain number, and then truncate; the third is to generate random numbers within the specified range;


1. Generate random numbers before a certain number

int thres; Generates a random number between [0, dis), noting that dis
printf ("%d\n", Random (Thres)) is not included;

2. Generate random numbers between two numbers

int Random (int m, int n)
{
		int pos, dis;
		if (M = = N) {return
			m;
		}
		else if (M > N) {
			pos = n;
			dis = m-n + 1;
			Return rand ()% dis + pos;
		}
		else
		{
			pos = m;
			dis = n-m + 1;
			Return rand ()% dis + pos;
		}

Test code:

int Testrand (int argc, _tchar* argv[])
{
		srand ((int) time (NULL));//For Random random seed
		int m = 7;
		int n =;
		for (int i = 0; i < ++i)
		{
			float f = Random (M, n);
			Std::cout << f << std::endl;
		}
		return 1;
}


Generate floating-point number random numbers


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.