谭浩强c++第三版6-13

#include<iostream>
#include<cmath>
using namespace std;

//用矩形法求定积分的通用函数

//矩形法  定积分的几何定义

double func_sin(double x)
{
	return sin(x);
}

double func_cos(double x)
{
	return cos(x);
}

double func_ex(double x)
{
	return exp(x);
}

double integral(double (*p)(double), double a, double b, int n)
{
	double x, h, s=0;
	h = (b - a) / n;                        //上限减下限 再等分成n份 
	x = a;                                     //从下限开始,计算n个矩形的面积 最后累加 
	for (int i = 0; i < n; i++)
	{
		x = x + h;                         //底加一个单位(即之前分的平均长度) 
		s += (*p)(x) * h;               //每个矩形的面积累加 
	}
	return s;
}

int main() {

	double a1, b1, a2, b2, a3, b3;
	double (*p)(double);                                  //指向函数的指针
	cout << "input a1,b1:";
	cin >> a1 >> b1;
	cout << "input a2,b2:";
	cin >> a2 >> b2;
	cout << "input a3,b3:";
	cin >> a3 >> b3;
	p = func_sin;
	cout << "the integral of sin(x) is :" << integral(p, a1, b1, 20) << endl;
	p = func_cos;
	cout << "the integral of cos(x) is :" << integral(p, a2, b2, 20) << endl;
	p = func_ex;
	cout << "the integral of exp(x) is :" << integral(p, a3, b3, 20) << endl;


	system("pause");
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值