2014-10-20 27 views
-1

所以我給了一個程序來創建,它涉及到讀取一個外部文件,該文件輸出一個類似於xy字段的圖像,我可以生成這麼多的東西,但是我陷入了死衚衕。 ..我刪除了#從而使圖書館可以閱讀使用遞歸的曲線下面的區域

數據文件包含

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 

/* 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; 

*/ 
+0

你的問題是什麼? – 2014-10-20 07:26:49

+0

您正在嘗試讀取整數,但您的文件包含實數。 ** ADD:**您需要檢查是否通過檢查流標記來正確讀入值。 – Galik 2014-10-20 07:29:27

回答

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; 
} 

如果你確實在輸入文件中有這些列標籤,你必須在一開始就吃掉它們。