C#生成随机数(中国大学MOOC网上的)

原文链接: https://www.icourse163.org/learn/PKU-1001663016?tid=1205988224#/learn/announce

C#生成随机数(中国大学MOOC网上的)_第1张图片

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;

public class Form1 : Form
{
    public Form1()
    {
        this.AutoScaleBaseSize = new Size(6, 14);
        this.ClientSize = new Size(400, 400);
        this.Paint += new PaintEventHandler(this.Form1_Paint);  // 重新绘制图片引发
        this.Click += new EventHandler(this.Redraw);            // 触发event事件,handler处理,redraw清理后重新绘制
    }
    static void Main()
    {
        Application.Run(new Form1());
    }
    private void Form1_Paint(object sender, PaintEventArgs e)   // PaintEventArgs 被触发的图层
    {
        graphics = e.Graphics;
        drawTree(11, 200, 380, 100, -PI / 2);
    }
    private void Redraw(object sender, EventArgs e)
    {
        this.Invalidate();                                      // 清理图层后重新调用Paint绘制
    }

    private Graphics graphics;                                  // GDI+绘图图面
    const double PI = Math.PI;
    double th1 = 35 * Math.PI / 180;
    double th2 = 25 * Math.PI / 180;
    double per1 = 0.6;
    double per2 = 0.7;

    Random rnd = new Random();                                  // 生成随机数
    double rand()
    {
        return rnd.NextDouble();
    }

    void drawTree(int n,
            double x0, double y0, double leng, double th)
    {
        if (n == 0) return;                         // 递归函数结束

        double x1 = x0 + leng * Math.Cos(th);       // 返回指定角度的余弦值
        double y1 = y0 + leng * Math.Sin(th);       // 返回指定角度的正弦值

        drawLine(x0, y0, x1, y1);

        drawTree(n - 1, x1, y1, per1 * leng * (0.5 + rand()), th + th1 * (0.5 + rand()));
        drawTree(n - 1, x1, y1, per2 * leng * (0.4 + rand()), th - th2 * (0.5 + rand()));
        if (rand() > 0.6)
            drawTree(n - 1, x1, y1, per2 * leng * (0.4 + rand()), th - th2 * (0.5 + rand()));
    }
    void drawLine(double x0, double y0, double x1, double y1)
    {
        graphics.DrawLine(
            Pens.Blue,
            (int)x0, (int)y0, (int)x1, (int)y1);
    }
}

 

你可能感兴趣的:(C#,随机树,C#)