[問題] TXT檔裡的矩陣輸入如何至程式裡的矩陣?

看板C_and_CPP (C/C++)作者 (No miracle)時間12年前 (2013/09/20 11:12), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
開發平台(Platform): (Ex: VC++, GCC, Linux, ...) vc++ 2010 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 小弟寫了一個計算反矩陣的程式 一開始我是直接在程式裡宣告一個矩陣來寫 double a[3][6] = {{1,-2,2}, {2,1,1}, {1,0,1}}; 執行起來沒問題,反矩陣計算也正確 但老師要我把原先宣告的矩陣修改成以TXT檔輸入 計算反矩陣後再輸出到另一個TXT檔 但是反矩陣計算變成下面結果: 1 0 0 0 0 0 0 0 0 0 -0.333333 -0.166667 0 -0.333333 -0.166667 0 -0.166667 1.16667 餵入的資料(Input): 預期的正確結果(Expected Output): 1 0 0 1 2 -4 0 1 0 -1 -1 3 0 0 1 -1 -2 5 錯誤結果(Wrong Output): 1 0 0 0 0 0 0 0 0 0 -0.333333 -0.166667 0 -0.333333 -0.166667 0 -0.166667 1.16667 程式碼(Code):(請善用置底文網頁, 記得排版) #include<iostream> #include <fstream> #include <string> #include <cmath> #include <sstream> #include "stdafx.h" using namespace std; const int n = 3; double a[n][n] ; int main() { ifstream inFile("matrix.txt"); string (*arr)[n] = new string[n][n] ; string line; int y = 0; while(getline(inFile , line)){ istringstream ss(line); string word; int x = 0; while(ss >> word) { arr[y][x] = word; x++;} y++ ;} inFile.close(); ofstream fout; fout.open("inv-matrix.txt"); for(int i =0 ; i<n ; i++) for(int j = 0 ; j<n ; j++) a[i][j] = atof(arr[i][j].c_str()); delete []arr; for (int i=0; i<3; ++i) for (int j=0; j<3; ++j) a[i][3+j] = 0; for (int i=0; i<3; ++i) a[i][3+i] = 1; for (int i=0; i<3; ++i) { if ( a[i][i] == 0) for (int j=i+1; j<3; ++j) if (a[j][i] != 0) { for (int k=i; k<6; ++k) swap(a[i][k], a[j][k]); // 交換上方row與下方row。 break; } double t = a[i][i]; for (int k=i; k<6; ++k) { a[i][k] /= t; } for (int j=0; j<3; ++j) if (i != j && a[j][i] != 0) { double t = a[j][i]; for (int k=i; k<6; ++k) a[j][k] -= a[i][k] * t; } } cout << "反矩陣已輸出"<<endl ; for(int i =0 ; i<3 ; i++) { fout<<endl; for(int j = 0 ; j<6;j++) fout<< a[i][j] << " "; } fout.close(); system("pause"); return(0); } 補充說明(Supplement): -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 27.245.31.253

09/20 12:38, , 1F
何不先輸出看看你讀到了什麼
09/20 12:38, 1F

09/20 12:51, , 2F
試過了,都讀不到 好像都出現0
09/20 12:51, 2F

09/21 17:27, , 3F
你應該先確定讀的到資料 再確定反舉證的方法沒寫錯
09/21 17:27, 3F

09/21 17:40, , 4F
string (*arr)[n+3] = new string[n][n+3] ;
09/21 17:40, 4F

09/21 17:42, , 5F
delete []arr; 不能放在for裡面
09/21 17:42, 5F

09/21 17:43, , 6F
加油 有問題先自己試試比較實在
09/21 17:43, 6F
文章代碼(AID): #1IExqx9j (C_and_CPP)
文章代碼(AID): #1IExqx9j (C_and_CPP)