起因

数学学习了正态分布和高尔顿钉板模型,打算用C#模拟一下

展示

高尔顿钉板模拟

代码

using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            gal oa = new gal();
            oa.infor();
            Console.WriteLine("请输入格子数(正整数):");
            string brid_input = Console.ReadLine();
            Console.WriteLine("请输入小球数(正整数):");
            string ball_input = Console.ReadLine();
            uint brid_input2 = Convert.ToUInt32(brid_input);
            uint ball_input2 = Convert.ToUInt32(ball_input);
            oa.galton(brid_input2,ball_input2);
            Console.ReadLine();
        }
    }

    class gal
    {
        public void infor()
        {
            Console.WriteLine("***********");
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.WriteLine("高尔顿钉板模型");
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.WriteLine(" ");
            Console.WriteLine("***********");
            Console.WriteLine(" ");
        }
        public void galton(uint Grid, uint Ball)
        {
            int[] grid = new int[Grid];
            int number = 0;
            
            for (int counter_ball = 1; counter_ball <= Ball; counter_ball++)
            {
                for(int times = 1; times <= (Grid - 1); times++)
                {

                    Random rd = new Random();
                    double l = rd.NextDouble()*2;
                    int rand = (int)l;
                    number += rand;
                }
                grid[number]++;
                number = 0;
            }

            Console.WriteLine("小球总数为{0},格数为{1}", Ball, Grid);
            
            for (int index = 0;index < grid.Length; index++)
            {
                int k = index + 1;
                Console.WriteLine("{0}号格子小球数为{1}", k, grid[index]);
            }
        }
    }
}

Git

Last modification:July 19th, 2020 at 06:00 pm
如果觉得我的文章对你有用,请随意赞赏