接口实例(C#,IShape)【C#】

这篇博客展示了如何在C#中使用接口IShape,定义了Circle和Rectangle类来实现该接口。Circle类已完整,Rectangle类需要补充Area和Perimeter方法。在Program类的Main方法中,读取用户输入并创建Rectangle对象,验证接口的实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

接口实例(C#,IShape)

题目描述

接口实例。接口和类如下图所示,根据给出代码,补写缺失的代码,然后在Program类的静态Main方法中验证所实现的类。

using System;
namespace Myinterface
{
    public interface IShape
    {
        double Perimeter();
        double Area();
    }
    class Circle : IShape
    {
        public double Radius { get; set; }
        public Circle(double r)
        {
            Radius = r;
        }
        public double Area()
        {
            return Math.PI * Radius * Radius;
        }
        public double Perimeter()
        {
            return 2 * Math.PI * Radius;
        }
    }
    class Rectangle : IShape
    {
            /////////////////////////////////////////////////////////////////
            
            //请填写代码,实现输出矩形的面积和周长

            /////////////////////////////////////////////////////////////////
        
    }

    class Program
    {
        static void Main(string[] args)
        {
            double w, h;
            double.TryParse(Console.ReadLine(), out w);
            double.TryParse(Console.ReadLine(), out h);
            Rectangle r = new Rectangle(w, h);
            Console.WriteLine("area={0},Perimeter={1}",r.Area(), r.Perimeter());
        }
    }
}

输入

输入矩形长、高,如
10
3
 

输出

area=30,Perimeter=26

样例输入

10

3

样例输出

area=30,Perimeter=26

提示

需要考虑输入非数字、负数等

        private double w, h;
        public Rectangle(double w,double h)
        {
            this.w = w;
            this.h = h;
        }
        public double Perimeter()
        {
            if (w <= 0 || h <= 0) return 0;
            return 2.0 * w + 2.0 * h;
        }
        public double Area()
        {
            if (w <= 0 || h <= 0) return 0;
            return w * h;
        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值