#include #include #include using namespace std; const int n = 4; class opt { private: long double a[n + 1][n + 1]; long double x[n + 1]; long double b[n + 1]; long double v[n + 1]; public: opt() { int i, j; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { a[i][j] = rand() % 5 + 1; /*cout << "a[" << i << "][" << j << "] = "; cin >> a[i][j];*/ } b[i] = rand() % 5 + 1; } } void printMatrix() { int i, j; cout << "Matrix A: \n"; for (i = 1; i <= n; i++) { for (j = 1; j <= n; j++) { cout.precision(2); cout.width(5); cout << a[i][j] << " "; } cout << endl; } } void printVectorB() { int i; cout << "Vector B: \n"; for (i = 1; i <= n; i++) { cout.precision(2); cout.width(5); cout << b[i] << " "; } cout << endl; } void printVectorX() { int i; cout << "Vector X: \n"; for (i = 1; i <= n; i++) { cout.precision(2); cout.width(5); cout << x[i] << " "; } cout << endl; } void calcX() { int i; for (i = 1; i <= n; i++) { x[i] = b[i] / a[i][i]; } } void getFineMatrix() { int j, k, aMax, h, t, temp; for (k = 2; k <= n; k++) { aMax = a[k][k]; h = k; for (t = k + 1; t <= n; t++) { if (abs(a[t][k]) > aMax) { aMax = abs(a[t][k]); h = t; } if (h != k) { for (j = k; j <= n; j++) { temp = a[k][j]; a[k][j] = a[h][j]; a[h][j] = temp; } temp = b[k]; b[k] = b[h]; b[h] = temp; } } } } void calcOpt() { int i, j, k, g, q, aMax, h, t, temp; long double r; for (k = 2; k <= n; k++) { aMax = a[k][k]; h = k; for (t = k + 1; t <= n; t++) { if (abs(a[t][k]) > aMax) { aMax = abs(a[t][k]); h = t; } if (h != k) { for (j = k; j <= n; j++) { temp = a[k][j]; a[k][j] = a[h][j]; a[h][j] = temp; } temp = b[k]; b[k] = b[h]; b[h] = temp; } } for (i = 1; i <= k - 1; i++) { r = a[k][i] / a[i][i]; for (j = i; j <= n; j++) { a[k][j] = a[k][j] - r * a[i][j]; } b[i] = b[i] - r * b[k]; } for (g = 1; g <= k - 1; g++) { r = a[g][k] / a[k][k]; for (q = k; q <= n; q++) { a[g][q] = a[g][q] - r * a[k][q]; } b[q] = b[q] - r * b[g]; } } } void vectorDeviations() { int i; cout << "Vector deviations " << endl; for (i = 1; i <= n; i++) { v[i] = a[i][i] * x[i] - b[i]; cout.precision(2); cout.width(5); cout << v[i] << " "; } } }; int main() { opt lab; lab.printMatrix(); lab.printVectorB(); cout << "--------Fine----------------\n"; lab.getFineMatrix(); lab.printMatrix(); lab.printVectorB(); cout << "------------------------------\n"; lab.calcOpt(); lab.printMatrix(); lab.printVectorB(); lab.calcX(); lab.printVectorX(); lab.vectorDeviations(); cin.get(); return 0; }