【小练习】循环、递归与概率:概率

1.练习代码-随机在正方形里面落1000个点,落在正方形内切圆中的点有多少个

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define LOOP 1000

int _tmain(int argc, _TCHAR* argv[])
{
	int rgnC = 0;
	for (int i=0; i<LOOP; i++)
	{
		int x = rand();
		int y = rand();
		if (x*x + y*y < RAND_MAX*RAND_MAX)
			rgnC++;
	}
	printf("%d\n", rgnC);
}

2.关键点分析

2.1计数过程

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#define LOOP 1000 //1000个点

int _tmain(int argc, _TCHAR* argv[])
{
	int rgnC = 0; //计数,计算落在圆内的点数
	for (int i=0; i<LOOP; i++)
	{
		int x = rand(); //随机落点的x坐标
		int y = rand(); //随机落点的y坐标
		if (x*x + y*y < RAND_MAX*RAND_MAX) //正方形边长为RAND_MAX*2,内切圆半径为RAND_MAX
			rgnC++;
	}
	printf("%d\n", rgnC);
}

2.2运算结果

当实验次数越大,(圆内落点数/总落点数) = 圆面积/正方形面积 = pi/4
此次程序得到778,778/1000 = 0.778, 与pi/4接近
【小练习】循环、递归与概率:概率