C#问题 求解答 ——(求面积相关问题)

(1)随机生成2个长方形和2个正方形,输出对应面积。(指的是每个图形的面积)
(2)增加2个三角形,如何改动程序使改动最小。

定义一个基类Shape,包含width,height,和计算面积的方法,然后三角形(需要另外新增一条边)继承自这个基类,重写下计算面积的方法就行。示例代码如下

img


using System;
namespace ConsoleApp1
{
    class Shape
    {
        public int width { get; set; }
        public int height { get; set; }
        public int GetArea()
        {
            return width * height;
        }
        public void ShowArea() { Console.WriteLine(width + "*" + height + "=" + this.GetArea()); }
    }
    class Triangle : Shape
    {
        public int thirdEdge { get; set; }
        public Triangle(int width, int height, int thirdEdge)
        {
            if (width + height < thirdEdge || width + thirdEdge < height || height + thirdEdge < width)
            {
                throw new Exception("无法构成三角形");
            }
            this.width = width;
            this.height = height;
            this.thirdEdge = thirdEdge;
        }
        public new double GetArea()
        {
            double p = (double)(width + height + thirdEdge) / 2;

            return System.Math.Sqrt(p * (p - width)* (p - height) *(p - thirdEdge));
        }
        public new  void ShowArea() { Console.WriteLine("三角形【" + width + "," + height + "," + thirdEdge + "】面积:" + this.GetArea()); }
    }
    class Program
    {
        static void Main(string[] args)
        {
            var rnd = new Random(Guid.NewGuid().GetHashCode());
            int width, height,thirdEdge;
            width = rnd.Next(10, 20);
            height = rnd.Next(10,20);
            Shape p1 = new Shape {width=width,height=height };
            p1.ShowArea();

            width = rnd.Next(10, 20);
            height = rnd.Next(10, 20);
            Shape p2 = new Shape { width = width, height = height };
            p2.ShowArea();

            width = rnd.Next(10, 20);
            Shape p3 = new Shape { width = width, height = width };
            p3.ShowArea();

            width = rnd.Next(10, 20);
            Shape p4 = new Shape { width = width, height = width };
            p4.ShowArea();


            width = rnd.Next(10, 20);
            height = rnd.Next(10, 20);
            thirdEdge = rnd.Next(10, 20);
            Triangle t1 = new Triangle(width, height, thirdEdge);
            t1.ShowArea();


            Console.ReadKey();
        }
    }
}

知道方法后用什么都可以,你可以设计一个继承类来做,也可以设计一个调用的方法来做,多样性的

   public string Area()
        {
            Random rd = new Random();
            int a = rd.Next(1, 5);
            int b = rd.Next(6, 10);
            int h = rd.Next(1, 5);

            //长方形面积公式 S=ab(a,b分别为长方形的长和宽,S为长方形的面积)
            decimal S_c = a * b;

            //正方形面积公式 S=aa(a,为正方形的边长,S为长方形的面积)
            decimal S_z = a * a;

            //三角形面积公式 S=(1/2)ah(a,h分别为三角形的底部边长和高,S为面积)
            decimal S_s = (1 / 2) * a * h;

            return $"长方形面积(长{a},宽{b}):{S_c},正方形面积(边长{a}):{S_z},三角形面积(底部边长{a},高{h}):{S_s}";
        }

用啥啊
这也不明确啊