C#实现一个计算器
一、运算类
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace lianxi
{
public class OPeration
{
private double _numberA = 0;
private double _numberB = 0;
public double NumberA
{
get { return _numberA; }
set { _numberA = value; }
}
public double NumberB
{
get { return _numberB; }
set { _numberB = value; }
}
public virtual double GetResult()
{
double result = 0;
return result;
}
}
}
在父类中定义 virtual 方法,如果在子类中进行了 override(重写),可以进行多态调用。 如果在子类中未进行 override,程序并不会报错。
二 、加法类
class OperationAdd:OPeration //继承运算类
{
public override double GetResult()
{
double result = 0;
result = NumberA + NumberB;
return result;
}
}
三、减法类
class OperationSub :OPeration//继承运算类
{
public override double GetResult()
{
double result = 0;
result = NumberA - NumberB;
return result;
}
}
四、 乘法类
class OperationMul:OPeration
{
public override double GetResult()
{
double result = 0;
result = NumberA * NumberB;
return result;
}
}
五、除法类
class OperationDiv:OPeration
{
public override double GetResult()
{
double result = 0;
if (NumberB == 0)
throw new Exception("除数不可以为零");
result = NumberA / NumberB;
return result;
}
}
五、OperationFactory类
class OperationFactory
{
public static OPeration createOperate(string operate)
{
OPeration oper = null;
switch (operate)
{
case "+":
oper = new OperationAdd();
break;
case "-":
oper = new OperationSub();
break;
case "*":
oper = new OperationMul();
break;
case "/":
oper = new OperationDiv();
break;
}
return oper;
}
}
六、客户端代码
Console.WriteLine("请输入第一个数字A:");
double numberA = double.Parse(Console.ReadLine());
Console.WriteLine("请输入运算符:+ - * /:");
string symbol = Console.ReadLine();
Console.WriteLine("请输入第二个数字B:");
double numberB = double.Parse(Console.ReadLine());
OPeration oper = OperationFactory.createOperate(symbol);
oper.NumberA = numberA;
oper.NumberB = numberB;
double result = oper.GetResult();
Console.WriteLine("结果是:"+ result);
Console.ReadLine();