您好,登錄后才能下訂單哦!
這個是用面向對象的方法來實現加,減,乘,除的計算,使用了“簡單工廠的設計模式”。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 簡單公司實現計算1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("請輸入第一個數字:");
double n1= Convert.ToDouble( Console.ReadLine());
Console.WriteLine("請輸入第二個數字:");
double n2= Convert.ToDouble(Console.ReadLine());
Console.WriteLine("請輸入一個操作符");
string oper= Console.ReadLine();
CalFather cal = Result(oper, n1, n2);
double result= cal.GetResult();
Console.WriteLine(result);
Console.ReadKey();
}
/// <summary>
/// 簡單工廠模式
/// </summary>
/// <param name="oper">傳入的操作符</param>
/// <param name="n1">第一個運算的數字</param>
/// <param name="n2">第二個運算的數字</param>
/// <returns></returns>
public static CalFather Result(string oper,double n1,double n2)
{
CalFather cal = null;
switch (oper)
{
case "+": cal = new Add(n1, n2);
break;
case "-": cal = new Sub(n1, n2);
break;
case "*": cal = new Ride(n1, n2);
break;
case "/":cal=new Chu(n1,n2);
break;
default: Console.WriteLine("輸入有誤");
break;
}
return cal;
}
}
/// <summary>
/// 父類模型,用abstract抽象函數來實現多態
/// </summary>
public abstract class CalFather
{
public double NumberOne
{
get;
set;
}
public double NumberTwo
{
get;
set;
}
public CalFather(double One,double Two)
{
this.NumberOne = One;
this.NumberTwo = Two;
}
public abstract double GetResult();
}
/// <summary>
/// 加法的子類
/// </summary>
public class Add:CalFather
{
public Add(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne + this.NumberTwo;
}
}
/// <summary>
/// 減法的子類
/// </summary>
public class Sub:CalFather
{
public Sub(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne - this.NumberTwo;
}
}
/// <summary>
/// 乘法的子類
/// </summary>
public class Ride:CalFather
{
public Ride(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne * this.NumberTwo;
}
}
/// <summary>
/// 除法的子類
/// </summary>
public class Chu:CalFather
{
public Chu(double one,double two):base(one,two)
{
}
public override double GetResult()
{
return this.NumberOne / this.NumberTwo;
}
}
}
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。