c#基于委托实现一个计算器功能的实例
时间: 2024-02-19 12:58:18 浏览: 119
下面是一个使用委托实现简单计算器功能的 C# 实例:
```csharp
using System;
namespace Calculator
{
class Program
{
delegate double MathOperation(double x, double y);
static void Main(string[] args)
{
Console.WriteLine("请输入两个数字和运算符,以空格分隔:");
string[] input = Console.ReadLine().Split(' ');
double num1 = double.Parse(input[0]);
double num2 = double.Parse(input[1]);
string op = input[2];
MathOperation operation = null;
switch (op)
{
case "+":
operation = Add;
break;
case "-":
operation = Subtract;
break;
case "*":
operation = Multiply;
break;
case "/":
operation = Divide;
break;
default:
Console.WriteLine("无效的运算符!");
break;
}
if (operation != null)
{
double result = operation(num1, num2);
Console.WriteLine("计算结果:{0}", result);
}
Console.ReadLine();
}
static double Add(double x, double y)
{
return x + y;
}
static double Subtract(double x, double y)
{
return x - y;
}
static double Multiply(double x, double y)
{
return x * y;
}
static double Divide(double x, double y)
{
if (y == 0)
{
Console.WriteLine("除数不能为零!");
return 0;
}
return x / y;
}
}
}
```
该程序首先要求用户输入两个数字和一个运算符,然后根据运算符选择相应的委托函数,最后将两个数字传递给委托函数并输出结果。注意,除法运算需要特殊处理除数为零的情况。
阅读全文