C++ 使用递归算法计算曲线下的面积

C++ 使用递归算法计算曲线下的面积,c++,function,recursion,C++,Function,Recursion,所以我得到了一个程序来创建它,其中包括读取一个外部文件,该文件输出一个类似于x-y场的图像,我能够产生这么多,但我陷入了死胡同。。。我移除了#以便可以阅读图书馆 数据文件包含 x values y values 20.00 0 20.02 15 20.04 27 20.06 39 20.08 54 20.10 65 20.12 75 20.14 84 20.16 93 20.18

所以我得到了一个程序来创建它,其中包括读取一个外部文件,该文件输出一个类似于x-y场的图像,我能够产生这么多,但我陷入了死胡同。。。我移除了#以便可以阅读图书馆

数据文件包含

x values    y values
20.00       0
20.02       15
20.04       27
20.06       39
20.08       54
20.10       65
20.12       75
20.14       84
20.16       93
20.18       101
20.20       108
20.22       113
20.24       116
20.26       115
20.28       112
20.30       107
20.32       100
20.34       92
20.36       83
20.38       74
20.40       64
20.42       53
20.44       39
20.46       27
20.48       15
20.50       0

/*此程序从文件中读取数字*/
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
河流充填;
int-x1,x2,y1,y2;
//打开文件。
infle.open(“xydata.txt”);
//从文件中读取数字
填充>>x1;//x1=20
填充>>y1;//y1=0
填充>>x2;//x2=20.02
填充>>y2;//y2=15
//关闭文件。
infle.close();
//计算曲线下方的总面积
双h,b,a,陷阱,最终陷阱;
a=(x2-x1);
b=(y2-y1);
陷阱=((a+b)/2);
最终陷阱=陷阱*b;
cout这是整个程序(但从stdin阅读-我相信你可以解决这个问题):

#包括
使用名称空间std;
int main(){
布尔第一次迭代=真;
浮动面积=0.0;
浮牛,oy,x,y;
而(cin>>x&&cin>>y){
如果(!第一次迭代)
面积+=(x-ox)*(y+oy)/2.0;
ox=x;oy=y;
第一次迭代=假;
}

您的问题是什么?您正在尝试读取整数,但您的文件包含实数。添加:您需要通过检查流标志来检查您是否正确读取了值。
/* This program reads numbers from a file. */
#include< iostream >
#include <fstream>
#include <iomanip>
#include <cmath>

using namespace std;

int main()
{
    ifstream inFile;
     int x1, x2, y1, y2;
    //Open the File.

   inFile.open("xydata.txt");

   //Read the numbers from the file

    inFile >> x1;  //x1 =20
    inFile >> y1;   // y1 = 0
    inFile >> x2;   // x2 =20.02
    inFile >> y2; //y2 = 15

    //Close File.
    inFile.close();




//Calculate the total Area underneath the curve


    double h, b, a, trap, final_trap;
    a = (x2 - x1);
    b = (y2 - y1);
    trap = ((a+b)/2);
    final_trap = trap*b;


    cout<<final_trap<<endl ;

    return 0;
}



/*

// Writing data into a File
int main()
{
ofstream outputFile
outputFile.open("xydata.dat")

cout << "Now writing data into the file" <<endl;

//Writing Area into the file
outputFile <<

//close this file
outputFile.close();
cout << "Done." << endl;
return 0;

*/
#include <iostream>
using namespace std;
int main() {

  bool first_iteration = true;
  float area = 0.0; 
  float ox, oy, x, y;
  while (cin>>x && cin>>y) {
    if (!first_iteration) 
      area += (x-ox) * (y+oy)/2.0;
    ox=x; oy=y;
    first_iteration=false;
  }
  cout << "Area is " << area << endl;
}