#include
#include
using namespace std;
int main(){
float fun(float x);
float a, b;
cout << "请输入函数X^2的定积分的下限a和上限b:";
cin >> a >> b;
int n = ;//将区间划分成50份
float h = (b - a) / n;//h是每个区间分大小
float s = ;//s是矩形的面积的和
float i = ;
for (i = a; i < b; i += h){
s = s + fun(i)*h;
}
cout << "\n结果是:" << s << endl;
cout << endl;
}
float fun(float x){
return pow(x, );
}
三:使用C语言实现下面三个函数的定积分求解
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
//使用矩形法来求定积分的通用函数
//p是函数指针,a是下界,b是上界,n是等分数
float integral(float(*p)(float), float a, float b, int n)
{
int i;
float area=;
float ew = (b - a) / n;
for (i = ; i <= n;i++)
area += (*p)(a + i*ew)*ew;
return area;
}
float f_sin(float x)
{
return sin(x);
}
float f_cos(float x)
{
return cos(x);
}
float f_exp(float x)
{
return exp(x);
}
int main()
{
float a, b,area;
float(*p)(float);
int n = ;
printf("test sin,input a,b:");
scanf("%f,%f", &a, &b);
p = f_sin;
area = integral(p, a, b, n);
printf("get value:%f\n", area);
printf("test cos,input a,b:");
scanf("%f,%f", &a, &b);
p = f_cos;
area = integral(p, a, b, n);
printf("get value:%f\n", area);
printf("test exp,input a,b:");
scanf("%f,%f", &a, &b);
p = f_exp;
area = integral(p, a, b, n);
printf("get value:%f\n", area);
system("pause");
return ;
}