1. 程式人生 > >c語言實現積分運算

c語言實現積分運算

用指標實現,最好先明白*p[4]和(*p)[4]的區別

int *p[4]; //定義一個指標陣列,該陣列中每個元素是一個指標,每個指標指向哪裡就需要程式中後續再定義了。
int (*p)[4]; //定義一個陣列指標,該指標指向含4個元素的一維陣列(陣列中每個元素是int型)。
區分int *p[n]; 和int (*p)[n]; 就要看運算子的優先順序了。
int *p[n]; 中,運算子[ ]優先順序高,先與p結合成為一個數組,再由int*說明這是一個整型指標陣列。
int (*p)[n]; 中( )優先順序高,首先說明p是一個指標,指向一個整型的一維陣列。

其次還要知道定積分的定義

#include<iostream>
#include<cmath>
using namespace std;
int main()
{
	float integral(float(*p)(float),float a,float b,int n);
	float fsin(float);
	float a1,b1,c,(*p)(float);
	int n;
	cout<<"輸入精確度數n:"<<endl;
	cin>>n;
	cout<<"input a1,b1:"<<endl;
	cin>>a1>>b1;
	p=fsin;
	c=integral(p,a1,b1,n);
	cout<<"the integral of sin(x) is:"<<c<<endl;
	return 0;
}
//聲明瞭一個指標p,
p指向一個具有一個float型別形參的函式,
這個函式返回一個float型值.
float integral(float(*p)(float),float a,float b,int n)
{
	int i;
	float x,h,s;
	h=(b-a)/2;
	x=a;//積分下限
	s=0;
	for(i=0;i<=n;i++)
	{
		x=x+h;//對函式的自變數x進行迭代
		s=s+(*p)(x)*h;對每一個小矩形累加求和
	}
	return(s);
}
float fsin(float x)
{
	return sin(x);
}