数值概念算法(随机数方法):利用概率论解决问题,
在求圆周率时的核心思想是:
在一个边长为r的正方形中,以中心点为圆心,r为直径作圆,则圆的面积是1/4πr平方,而正方形面积是r平方。二者比值就是1/4π。
所以随机向该正方形投入点,其中落在圆内的概率的4倍就是圆周率。
源码:
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int n);
5:
int main()
7: {
double PI;
int n;
);
, &n);
12: PI = GetPI(n);
, PI);
return 0;
15: }
16:
int n)
18: {
int nInCircle = 0;
float x, y;
int nCount = n;
while (nCount)
23: {
24: x = random(101);
25: y = random(101);
if (x*x + y*y <= 10000)
27: {
28: nInCircle++;
29: }
30: nCount--;
31: }
return 4.0*nInCircle/n;
33: }