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

看板C_and_CPP作者 (凱西)時間5年前發表 (2019/12/31 06:30), 5年前編輯推噓0(000)
留言0則, 0人參與, 最新討論串2/3 (看更多)
※ 引述《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; } -- 有沒有準備好我不知道, 但我已經做了我最好的選擇。 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 203.64.168.94 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1577773832.A.B07.html ※ 編輯: devcc (203.64.168.94 臺灣), 12/31/2019 14:33:28
文章代碼(AID): #1U2ki8i7 (C_and_CPP)
文章代碼(AID): #1U2ki8i7 (C_and_CPP)