c++ - 计算积分的算法
问题描述
**
我使用平均方法编写了一个程序,我们以两种方式计算它——通过给定的 n 分区数和给定的精度。我是否需要编写检查以使分区数不为零或负数(即写保护)或防止非数字输入?**
#include <iostream>
#include <math.h>
#include <conio.h>
using namespace std;
#pragma hdrstop
#pragma warning(disable : 4996)
double f(double);
double Metod(double (*f)(double), double, double, int);
void main()
{
double a, b, eps, I1, I2, pogr;
int n, n1, kod;
cout << "If a=-2, b=3, Int=5,983" << endl;
do {
cout << "Input a:";
cin >> a;
cout << "Input b:";
cin >> b;
cout << "\n\t Input 1 - n, Else - eps : ";
cin >> kod;
if (kod == 1) {
cout << "Input n: ";
cin >> n;
I1 = Metod(f, a, b, n);
}
else {
cout << "Imput eps: ";
cin >> eps;
n1 = 2;
I1 = Metod(f, a, b, n1);
do {
n1 *= 2;
I2 = Metod(f, a, b, n1);
pogr = fabs(I2 - I1);
I1 = I2;
} while (pogr > eps);
cout << "\t n=" << n1 << endl;
}
cout << "\n\t Integral= " << I1 << endl;
cout << "\n Repeat - 1, Else - Exit " << endl;
} while (getch() == '1');
}
double f(double x)
{
return 4 * x - 7 * sin(x);
}
double Metod(double (*f)(double x), double a, double b, int n)
{
double s = 0, h, x;
h = (b - a) / n;
for (x = a + h / 2; x <= b; x += h) {
s = s + f(x);
}
return h * s;
}
解决方案
推荐阅读
- python - Numpy savetxt 将一维数组保存为列
- tsql - GROUP BY HAVING 逻辑不起作用(最小/最大日期)
- tensorflow - Tensorflow 1.13.1 无法识别 GPU
- c - 如何遍历多个数组
- mysql - 我如何计算每位讲师教授的学生数量而不包括重复项?
- java - 如何在 Visual Studio Code 中修改 Java 样板代码生成?
- mysql - MySQL日期子查询和两行唯一
- validation - 服务器端验证以验证上传的文件是实际图像
- javascript - IOS上的vimeo播放器自定义播放器具有全屏按钮
- javascript - 正则表达式 javascript 搜索词但忽略几个词