using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void count(Random rand)
{
Console.Write("请输入运算的次数:");
Int32 N = 0;
Int32 K = 0;
try
{
string strinput = Console.ReadLine();
Int32 M = Convert.ToInt32(strinput);
for (Int32 i = 0; i < M; i++)
{
double x = rand.NextDouble();
double y = rand.NextDouble();
if (x * x + y * y <= 1)
{
N++;
if (x + y >= 1) K++;
}
}
double result1 = (double)4 * N / M;
Int32 J = M - N;
double result2=(double)(4*K+2*J)/(K+J);
double wucha1=result1-System.Math.PI;
double wucha2 = result2 -System.Math.PI;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("经过{0}次随机事件后,算法1圆周率为{1},误差为{2}.", M, result1,wucha1);
Console.WriteLine("经过{0}次随机事件后,算法2圆周率为{1},误差为{2}./n", M, result2,wucha2 );
Console.ForegroundColor = ConsoleColor.White;
}
catch {
Console.ForegroundColor = ConsoleColor.Gray;
Console.Write("输入有误,");
}
}
static void Main(string[] args)
{
Console.WriteLine("****************************");
Console.WriteLine("随机算法求圆周率演示程序/n");
Console.WriteLine("****************************/n");
Console.ForegroundColor = ConsoleColor.White;
Random rand = new Random();
while (true)
{
count(rand);
}
}
}
}