C#第二次实验:面向对象编程

注:本文由我原创,从本人的另一个CSDN账号(已注销)复制而来。由于原始.doc文件丢失,所以直接从原推文拷贝,所以图片可能有水印。

实验一

【实验目的】求三角形的面积

【实验要求】

用“方法的参数数组”、“接口”、“构造函数”、“类继承”、至少四种方法实现三角形的面积的方法;

最简单的就是根据长方形的面积=×宽推断出平行四边形的面积=×,因为两个一样的三角形可组成一个平行四边形,可得面积计算公式:

三角形的面积=×÷2 [S=ah÷2]

或者是:

三角形任意两边之积×这两边的夹角的正弦值÷2 [S=ab×sin×1/2]

(方法一,[S=ah÷2]

【实验代码】

using System;
namespace homework2_1
{
    //定义接口IPartOne
    public interface IPartOne       
    {
        void SetDataOne(string dataOne);        //构造函数
    }
    //WritesthClass类派生自接口IPartOne
    public class WritesthClass : IPartOne       
    {
        private string DataOne;
        //
        public void SetDataOne(string dataOne)
        {
            DataOne = dataOne;
            Console.WriteLine("{0}", DataOne);
        }
    }
    //定义抽象基类:Shape
    public abstract class Shape    
    {
        public Shape() {; }
    }
    //对Rectangular类的定义。Circle为Shape类的子类;
    public class Rectangular: Shape     
    {
        //Length和Width是Rectangualr的属性;
        protected double Length, Width;     
        public Rectangular ()
        {
            Length = 0; 
            Width = 0;      //变量Length和Width的初始化;
        }

        public Rectangular (double Length,double Width)
        {
            this.Length = Length;
            this.Width = Width;
        }
        public double MianjiIs()
        {
            return Length * Width;
        }
    }
    public class Triangle:Rectangular       //三角形类从矩形类中派生
    {
        public Triangle (double Length,double Height)       //方法,有参数,其中为形参,主函数中的参数是实参。
        {
            this.Length = Length;
            this.Width = Height;
        }    
        public double MianjiIs()
        {
            return 0.5* Length * Width;
        }
    }
    class Program
    {
        public static void Main(string[] args)
        {          
            Console.WriteLine("请输入底边和高的长度,以回车键间隔:");
            double i = Convert.ToInt32(Console.ReadLine());
            double j = Convert.ToInt32(Console.ReadLine());
            Triangle Tri = new Triangle(i, j);       //实例化,并且设定三角形的三个边
            WritesthClass a = new WritesthClass();
            a.SetDataOne("Triangle area is:");
            Console.WriteLine("{0}", Tri.MianjiIs());
        }
    }
}

【运行结果】
将底边和高分别设为34,得到的面积为:<

你可能感兴趣的:(C#,c#,类)