[問題] TXT檔裡的矩陣輸入如何至程式裡的矩陣?
開發平台(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
09/20 12:51, 2F
推
09/21 17:27, , 3F
09/21 17:27, 3F
→
09/21 17:40, , 4F
09/21 17:40, 4F
→
09/21 17:42, , 5F
09/21 17:42, 5F
→
09/21 17:43, , 6F
09/21 17:43, 6F
C_and_CPP 近期熱門文章
PTT數位生活區 即時熱門文章