曲线下面积的C ++程序。 (上限)?

时间:2016-12-11 00:48:18

标签: c++ algorithm

这就是我的上限。我对n的值是5.但是我觉得我搞砸了某个地方,因为当我用手计算它时它的值不一样。有谁知道我的程序有什么问题?

#include<iostream> 
#include<stdlib.h> 
#include<math.h> 
#include<iomanip> 
#include<fstream> 

using namespace std; 
double f(double x) 
{ 
    return (0.6*pow(x,2)) +4; 
} 
int main ( ) 
{ 

    double a, b, delx, x, area; 
    int n; 

    cout << "Welcome. To begin, please enter a value for 'a' followed by a value for 'b'. \n"; 
    cin>>a>>b; 
    cout << "You have entered a = " << a<<" & b = " <<b <<". Now, input an n value \n"; 
    cin >>n; 

    delx = (b-a)/n; 
    area = 0; 

    for (int i=0;i<=n;i++) 
    { 
        area = area + f(a+i*delx)*delx; 
    } 

    cout << "The area under the curve of f(x) = 0.6x^2 + 4 is "; 
    cout << setprecision(5) << area; 


    system ("pause"); 

}

1 个答案:

答案 0 :(得分:1)

int main()
{
    double a=0, b=5; //a: lower limit, b: upper limit of integration
    int n=20; //the number of intervals
    double dx = (b-a)/n; //step size
    double area = 0; //our goal to find

    for (int i=0;i<n;i++) 
    { 
        //using trapezoidal method
        //the area of a trapezoid is (lower base + upper base)*height/2
        //f(a+i*dx): upper base, f(a+(i+1)*dx): lower base
        //dx: height of the trapezoid
        area = area + (f(a+i*dx)+f(a+(i+1)*dx))*dx/2.0; 
    } 

    std::cout<<area;

}

虽然您的方法不正确(但不理想),但梯形方法会更快收敛。在您的方法中,您可以将n(间隔数)设置为高于梯形的数字,以获得相似的准确度。