随机算法求圆周率演示程序源代码

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);
           
           
            }
              
         

        }


    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值