Re: [問題] C++ 讀檔(.dat)>跨行計算>輸出

作者: devcc (遊俠)   2019-12-31 14:30:30
※ 引述《devcc (凱西)》之銘言:
: 問題(Question):
: 我想做一個簡單的資料分析處理
: 已經先有dat檔
: 因為數值變動很大,想做前兩個或是前三個數值結果相加平均
: 同行的計算平均會,但跨行的不知道怎麼去寫計算
: 餵入的資料(Input):
: ex:
: .DAT
: 1 10
: 2 3
: 3 11
: 4 9
: 5 7
: 6 1
: 預期的正確結果(Expected Output):
: 以前兩個做平均出來希望如下
: 1 6.5
: 2 7
: 3 10
: 4 8
: 5 4
經過半天研究 因為主要我不知道原本的數據量會有多少
這是我寫的code 希望對別人有幫助
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main ()
{
///計算行數
ifstream fin;
int line = 0;
string tmps;
fin.open("C3_SM_1.dat",ios::in);//開檔讀取
while(getline (fin,tmps))
{
line++;//一行一行讀,每讀一行就加一
}
fin.close();//關閉文件
cout <<"此檔共"<< line <<"行"<< endl;//輸出行數
///寫入陣列
int i,j,a,b;
b=3;
a=line;
double matrix[a][b];
ifstream input("C3_SM_1.dat",ios::in);
for(i=0;i<a;i++)
for(j=0;j<(b-1);j++)
input>>matrix[i][j];
input.close();
///開檔+計算
ofstream fout("C3_SM_1_arr.dat");
if(!fout){ cout << "開檔失敗" << endl; } // 檢查開檔成功與否
for(i=0;i<(a-2);i++)
{
matrix[i][2]= (matrix[i][1]+matrix[(i+1)][1]+matrix[(i+2)][1])/3;
fout<<matrix[i][0]<<" "<<matrix[i][2]<<endl;
}
///輸出顯示
for(i=0;i<(a-2);i++)
for(j=0;j<b;j++)
cout<< matrix[i][j]<<" "<<endl;
fout.close(); // 關閉檔案
return 0;
}

Links booklink

Contact Us: admin [ a t ] ucptt.com