接口實例(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;}
?