首页 > 解决方案 > 计算积分的算法

问题描述

**

我使用平均方法编写了一个程序,我们以两种方式计算它——通过给定的 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;
}

标签: c++integral

解决方案


推荐阅读