1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | #include <iostream> #include <string> #include <sstream> #include <fstream> /* input.txt 的內容如下 2 2 -1 0 1 -1 -1 2 -3 1 1 1 -2 0 -1 0 0 1 1 1 */ using namespace std; int main(int argc, char *argv[]) { int Row = 0, Column = 0, LeadOne=0; string GetNum; fstream InPut, OutPut; double **M = new double*[200], temp; for (int i=0;i<200;i++) M[i] = new double[200]; InPut.open ("input.txt", ios::in); OutPut.open ("output.txt", ios::out); if (!InPut) cerr << "Failed to open file!"; else { while (!InPut.eof()) { getline(InPut, GetNum); stringstream TransNum(GetNum, istringstream::in); while (!TransNum.eof()) { TransNum >> M[Row][Column]; Column++; } Row++; if (!InPut.eof()) Column=0; } } for (int r=0; r<Row; r++) { int i = r, LeadTemp = LeadOne; while (M[i][LeadTemp] == 0) { i++; if (i == Row) { i = r; LeadTemp++; if (LeadTemp == Column) break; } for (int c=0; c<Column; c++) { temp = M[i][c]; M[i][c] = M[r][c]; M[r][c] = temp; } } if (M[r][LeadOne] != 0 && LeadOne != Column-1) { temp = M[r][LeadOne]; for (int m=0; m<Column; m++) M[r][m] = M[r][m]/temp; } for (int j=0; j<Row; j++) { if (j!=r) { temp = M[j][LeadOne]; for (int p=0; p<Column; p++) M[j][p] -= temp*M[r][p]; } } LeadOne++; } for (int x=0; x<Row; x++) { for (int y=0; y<Column; y++) OutPut << M[x][y] << " "; OutPut << '\n'; } for (int i=0; i<200; i++) delete [] M[i]; delete [] M; InPut.close(); OutPut.close(); return EXIT_SUCCESS; } |
Direct link: https://paste.plurk.com/show/314623