1.本段程序实现的功能
1)通过积分的几何意义计算积分:计算函数曲线与坐标轴围成部分的面积,方法为将面积分为小块的矩形,依次计算矩形的面积并相加
2)程序通过Integration函数计算积分,该函数有三个参数:attr、left、right,分别代表:选用哪个函数进行计算、积分下界和积分上界。写一个函数,参数和返回值都是double类型,只要在其上加上[RemarkAttribute("函数标识")],并将“函数标识”字符串传入到attr参数中,Integration函数就可以自动选择这个函数进行积分计算了
2.函数实现
/// <summary>
/// 示例函数1:f(x)=x*2
/// </summary>
/// <param name="x">自变量x</param>
/// <returns>因变量f(x)</returns>
[RemarkAttribute("Double")]
public static double Function1(double x)
{
return x * 2;
}
/// <summary>
/// 示例函数2:f(x)=x^2
/// </summary>
/// <param name="x">自变量x</param>
/// <returns>因变量f(x)</returns>
[RemarkAttribute("Square")]
public static double Function2(double x)
{
return x * x;
}
/// <summary>
/// 示例函数3:(x-1)^2+y^2=1 (y>=0)
/// </summary>
/// <param name="x">自变量x</param>
/// <returns>因变量f(x)</returns>
[RemarkAttribute("HalfCircle")]
public static double Function3(double x)
{
double result = 1 - (x - 1) * (x - 1);
return Math.Sqrt(result >= 0 ? result : 0);
}
/// <summary>
/// 特性 RemarkAttribute,用在函数上,其 Remark 属性决定了
/// 积分函数 Integration 应该选择程序中的哪个函数进行计算
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class RemarkAttribute : Attribute
{
string remark;
public string Remark
{
get { return remark; }
}
//构造函数
public RemarkAttribute(string comment)
{
remark = comment;
}
}
/// <summary>
/// 计算积分
/// </summary>
/// <param name="attr">原函数RemarkAttribute特性名</param>
/// <param name="left">积分下界</param>
/// <param name="right">积分上界</param>
/// <returns></returns>
public static double Integration(string attr, double left, double right)
{
//1.找到 RemarkAttribute 特性为 attr 的方法(需要 using System.Reflection;)
MethodInfo[] mi = typeof(Program).GetMethods();
MethodInfo mthd = null;
foreach (MethodInfo m in mi)
{
Type t2 = typeof(RemarkAttribute);
RemarkAttribute ra = (RemarkAttribute)Attribute.GetCustomAttribute(m, t2);
if (ra != null && ra.Remark == attr)
{
mthd = m;
break;
}
}
//2.如果没有找到 RemarkAttribute 特性为 attr 的方法则报出异常
if (mthd == null)
{
throw new Exception("没有特性为 " + attr + " 的方法");
}
//3.调用找到的方法,通过积分的几何意义求解面积
double result = 0;
for (double i = left; i < right; i += 1E-6)
{
result += (double)mthd.Invoke(null, new object[] { i + 5E-7 }) * 1E-6;
}
return result;
}
3.Main函数调用
static void Main(string[] args)
{
Console.WriteLine("f(x)=x*2 在 [0,2] 的积分:");
Console.WriteLine(Integration("Double", 0, 2).ToString("#0.000"));
Console.WriteLine("f(x)=x^2 在 [0,2] 的积分:");
Console.WriteLine(Integration("Square", 0, 2).ToString("#0.000"));
Console.WriteLine("(x-1)^2+y^2=1 (y>=0) 在 [0,2] 的积分:");
//即函数 f(x)=1-(x - 1)*(x-1) (0<=x<=2) 在 [0,2] 的积分
Console.WriteLine(Integration("HalfCircle", 0, 2).ToString("#0.000"));
Console.ReadLine();
}
4.运行示例