mikolajmki

aan_11

Dec 20th, 2021 (edited)
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.92 KB | None | 0 0
  1. #include <iostream>
  2. #include <math.h>
  3.  
  4. using namespace std;
  5.  
  6.  
  7. void wyswietlMacierz(double l[3][3])
  8. {
  9.     for (int j = 0 ; j < 3 ; j ++)
  10.     {
  11.         cout << "| ";
  12.         for (int i = 0 ; i < 3 ; i ++) cout << l[j][i] << " ";
  13.         cout << "|" << endl;
  14.     }
  15. }
  16.  
  17.  
  18. void stworzMacierz(int n, double a[3][3], double l[3][3])
  19. {
  20.     double suma;
  21.  
  22.     for (int s = 0 ; s < n ; s ++)
  23.     {
  24.         for (int j = s ; j < n ; j ++)
  25.         {
  26.             suma = 0;
  27.             for (int i = 0 ; i < s ; i ++) suma += l[j][i] * l[s][i];
  28.             l[j][s] = a[j][s] - suma;
  29.  
  30.             if (s == j) l[j][s] = sqrt (l[j][s]);
  31.             else l[j][s] /= l[s][s];
  32.         }
  33.     }
  34.  
  35.     wyswietlMacierz(l);
  36. }
  37.  
  38.  
  39. int main ()
  40. {
  41.     double a[3][3] = {{1, 2, 3}, {2, 8, 10}, {3, 10, 22}};
  42.     double b[3] = {1, 3, 7};
  43.     double l[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
  44.     double x[3];
  45.     double y[3];
  46.     int n = 3;
  47.     float s = 0;
  48.     double t;
  49.  
  50.     cout << "Stworzenie macierzy L" << endl;
  51.     stworzMacierz(n, a, l);
  52.  
  53.     cout << endl << "Obliczanie wektora y" << endl;
  54.     y[0] = l[0][0];
  55.  
  56.     for (int i = 1 ; i < n ; i ++)
  57.     {
  58.         s = 0;
  59.         for (int j = 0 ; j < i ; j ++) s = s + l[i][j] * y[j];
  60.         y[i] = (b[i] - s) / l[i][i];
  61.     }
  62.  
  63.     for (int i = 0 ; i < 3 ; i ++) cout << "y[" << i << "] = " << y[i] << endl;
  64.  
  65.     cout << endl << "Transpozycja macierzy L" << endl;
  66.  
  67.     for (int j = 0 ; j < n - 1 ; j++)
  68.     {
  69.         for (int i = j + 1 ; i < n ; i ++)
  70.         {
  71.             t = l[j][i];
  72.             l[j][i] = l[i][j];
  73.             l[i][j] = t;
  74.         }
  75.     }
  76.  
  77.     wyswietlMacierz(l);
  78.  
  79.     cout << endl << "Obliczanie wektora x" << endl;
  80.  
  81.     x[2] = y[2] / l[2][2];
  82.     x[1] = (y[1] - (l[1][2] * x[2])) / l[1][1];
  83.     x[0] = (y[0] - ((l[0][1] * x[1]) + l[0][2] * x[2])) / l[0][0];
  84.  
  85.     for (int i = 0 ; i < 3 ; i ++) cout << "x[" << i << "] = " << x[i] << endl;
  86. }
Add Comment
Please, Sign In to add comment