归零# 2023-10-24 11:43 采纳率: 0%
浏览 1

C#物联网程序设计基础 类和对象 习题

定义一个rectangle类,有两个属性一— length和width,其默认值均为1,完成以下内容:
①定义两个成员函数,分别计算长方形的周长和面积。
②为length, width属性定义设置set函数和get函数。
③使用set函数验证两个属性值均在0~20之间。
④输出给定长度和宽度后长方形的周长和面积。

  • 写回答

1条回答 默认 最新

  • threenewbee 2023-10-24 12:02
    关注
    using System;
    using static System.Console;
    
    class Rectangle
    {
        private int _length = 1;
        private int _width = 1;
    
        public int Length
        {
            get => _length;
            set => _length = value < 0 || value > 20 ? 0 : value;
        }
    
        public int Width
        {
            get => _width;
            set => _width = value < 0 || value > 20 ? 0 : value;
        }
    
        public int GetPerimeter() => (Length + Width) * 2;
    
        public int GetArea() => Length * Width;
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle rect = new Rectangle();
            int length = int.Parse(ReadLine());
            rect.Length = length;
            int width = int.Parse(ReadLine());
            rect.Width = width;
            int perimeter = rect.GetPerimeter();
            int area = rect.GetArea();
            WriteLine($"周长: {perimeter}");
            WriteLine($"面积: {area}");
        }
    }
    

    img

    评论

报告相同问题?

问题事件

  • 创建了问题 10月24日