About the use of random function

Random function is very simple, and only a:
RAND ()
This function returns an integer between 0 and 32767. (32767 do not need to remember this number, probably know the scope on the list)
the function in the header file <stdlib.h>, the references before using the recall.

[Simple Test]

在这#include <stdio.h>
#include <stdlib.h>

int main()
{
	int r;
	for(int i=0; i<10; i++)
	{
		r = rand();
		printf("%d\n", r);
	}

	return 0;
}里插入代码片

Copy
After the execution, output 10 can be seen random numbers.

[Random function specified range]

In practice, we often have to generate random function specified range, we usually find ways to use the remainder. For example, generates a random number between 0 and 9, the random number just to produce any number of remainder can be divided by 10. Remainder operand symbol is%, we can do this:

r = rand() % 10;

Modified after performing the previous test program can be seen, the resulting number is less than 10.

If you ask what is between 1 to 6 it?
r = rand ()% 6 + 1;

No matter what kind of range of the random function generated by various calculations are the range of the random numbers [0, 32767] need to modify the range of their
random seed]

Do a number of tests, we found a problem: Although the numbers are generated randomly, but each time the sequence of numbers generated are the same. To solve this problem, we need to use the "random seed." (Meaning that each time a random number is fixed, pro-test)
thus introduced into the next function
generating random function principle is simple, is to: a value before the value of the random function, determines a random function.

According to this principle we can know: as long as the value of the first random function is determined, then the latter is to determine the sequence of numbers. If we want to get a different sequence of numbers, we need to determine the value of a random function to set the first random function value set is called "random seed." Easy to know, random seed set once.

Random seed is provided as a function of:
srand (seed);

Usually, we use the current time to do random seed:
srand ((unsigned) Time (NULL));

Because the use of time function, so remember to quote <time.h>.

[Drawing Application]

To a simple procedure, the point on the screen painted any color anywhere (Press any key to exit):

在#include <graphics.h>
#include <stdlib.h>
#include <conio.h>
#include <time.h>

int main()
{
	srand( (unsigned)time( NULL ) );

	initgraph(640, 480);

	int x, y, c;
	while(!kbhit())
	{
		x = rand() % 640;
		y = rand() % 480;
		c = RGB(rand() % 256, rand() % 256, rand() % 256);
		putpixel(x, y, c);
	}

	closegraph();
	return 0;
}`这里插入代码片
Released nine original articles · won praise 3 · Views 713

Guess you like

Origin blog.csdn.net/delete_bug/article/details/104239941