C#——《C#语言程序设计》实验报告——泛型与集合——“画树”程序

一、实验目的

  1. 掌握运算符重载。
  2. 掌握索引符的编写。
  3. 掌握常用非泛型集合类和集合类的使用;
  4. 掌握可空类型的使用

 

二、实验内容

  1. 改进“画树”的例子程序,画出不同风格的“树”来。

原先的例子中,两棵子树的生长点都在(x1,y1),我们改进一下,将两棵子树的生长点不同,在(x1,y1)及(x2,y2)。

程序中可以加上一些控件(如滚动条、文本框等),以方便用户修改角度(例子中是35及30度)、长度(例子中是per1,per2),这里又加了两子树的位置的系数(即点0至点2的长度是点0至点1的长度的多少倍k)。

(例子中,x1=x0+leng*cos(th), 这里要加个x2=x0+leng*k*cos(th) )。

还可以加上颜色、粗细、是否随机等选项,全在于发挥你的想像力!

源代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace Homework18
{public partial class Form1 : Form{public Form1(){InitializeComponent();this.AutoScaleBaseSize = new Size(6, 14);this.ClientSize = new Size(500, 400);//窗体大小this.Paint += new PaintEventHandler(this.Form1_Paint);this.Click += new EventHandler(this.Redraw);//重画}private void Form1_Paint(object sender, PaintEventArgs e){graphics = e.Graphics;drawTree(10, 250, 350, 100, -PI / 2);drawTree(10, 150, 350, 100, -PI / 2);}private void Redraw(object sender, EventArgs e){ this.Invalidate(); }//鼠标点击,重新画private Graphics graphics;const double PI = Math.PI;double th1 = 40 * Math.PI / 180;double th2 = 30 * 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, n / 3);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, double width){if ((int)width * 3 <= 1)graphics.DrawLine(new Pen(Color.Red, (int)width), (int)x0, (int)y0, (int)x1, (int)y1);elsegraphics.DrawLine(new Pen(Color.Green, (int)width), (int)x0, (int)y0, (int)x1, (int)y1);}}
}

运行结果 

三、实验心得与体会

  1. 掌握运算符重载。
  2. 掌握索引符的编写。
  3. 掌握常用非泛型集合类和集合类的使用;
  4. 掌握可空类型的使用

参考文章

https://blog.csdn.net/zhonghuachun/article/details/75040598


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部