用C语言写定积分的通用函数:sin(x),cos(x),eX.

#include
/************************************************************/
/*sin,cos,exp函数已经存在于系统的数学函数库中,程序开头需要定义math头文件*/
/************************************************************/
#include
/****************主函数**************************************/
int main()
{
	float integral(float(*)(float), float, float, int);
	float fsin(float);
	float fcos(float);
	float fexp(float);
	float a1, b1, a2, b2, a3, b3, c, (*p)(float);//定义一个float类型的指针
	int n = 20;
	//输入积分上下限
	printf("enter a1,b1:\n");
	scanf("%f%f", &a1, &b1);
	printf("enter a2,b2:\n");
	scanf("%f%f", &a2, &b2);
	printf("enter a3,b3:\n");
	scanf("%f%f", &a3, &b3);

	p = fsin;//用float型指针指向fsin函数
	c = integral(p, a1, b1, n);
	printf("sin(x)=%f\n", c);

	p = fcos;//用float型指针指向fcos函数
	c = integral(p, a2, b2, n);
	printf("cos(x)=%f\n", c);

	p = fexp;//用float型指针指向exp函数
	c = integral(p, a3, b3, n);
	printf("exp(x)=%f\n", c);
	return 0;
}
float integral(float(*p)(float), float a, float b, int n)
{
	int i;
	float x, h, s;
	h = (b - a) / n;//牛顿莱布尼茨公式运用
	x = a;
	s = 0;
	for (i = 0; i < n; i++)
	{
		x = x + h;
		s = s + (*p)(x)*h;
	}
	return (s);
}
float fsin(float x)
{
	return sin(x);
}
float fcos(float x)
{
	return cos(x);
}
float fexp(float x)
{
	return exp(x);
}

 

你可能感兴趣的:(AndroidStudio)