当前所在位置:珠峰网资料 >> 计算机 >> 软件水平 >> 正文
随机算法求圆周率演示程序源代码
发布时间:2010/11/10 15:27:08 来源:www.xue.net 编辑:城市总裁吧
   共享一下随机算法求圆周率演示程序源代码
  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);
  }
  }
  }
  }
广告合作:400-664-0084 全国热线:400-664-0084
Copyright 2010 - 2017 www.my8848.com 珠峰网 粤ICP备15066211号
珠峰网 版权所有 All Rights Reserved