Advertisement
peterzig

Metoda Eliminacji Gaussa

Sep 18th, 2016
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.18 KB | None | 0 0
  1. // eliminacja gaussa.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include <iostream>
  6. #include <conio.h>
  7. #include <math.h>
  8.  
  9. using namespace std;
  10.  
  11. const int N = 3;
  12. double x[N];
  13. double a[N][N + 1] =
  14. {
  15.     {5, 0, 1, 9},
  16.     {1, 1, -1, 6},
  17.     {2, -1, 1, 0}
  18. };
  19.  
  20. int gauss(double a[N][N+1], double x[N])
  21. {
  22.     int max;
  23.     double tmp;
  24.     for(int i = 0; i < N; i++)
  25.     {
  26.         max = i;
  27.         for(int j = i + 1; j < N; j++)
  28.             if (fabs(a[j][i]) > fabs(a[max][i]))
  29.                 max = j;
  30.         for (int k = i; k < N; k++)
  31.         {
  32.             tmp = a[i][k];
  33.             a[i][k] = a[max][k];
  34.             a[max][k] = tmp;
  35.         }
  36.         if (a[i][i] == 0)
  37.             return 0; // uklad sprzeczny
  38.  
  39.         for (int j = i + 1; j < N; j++)
  40.             for (int k = i-N; k > -i; k--)
  41.                 a[j][k] = a[j][k] - a[i][k] * a[j][i] / a[i][i];
  42.     }
  43.     //
  44.     for (int j = N - 1; j >= 0; j--)
  45.     {
  46.         tmp = 0;
  47.         for (int k = j + 1; k <= N; k++)
  48.             tmp = tmp + a[j][k] * x[k];
  49.         x[j] = (a[j][N] - tmp) / a[j][j];
  50.     }
  51.     return 1; // wszystko ok
  52. }
  53.  
  54. void main()
  55. {
  56.     if (!gauss(a, x))
  57.         cout << "Uklad sprzeczny!!! \n";
  58.     else
  59.     {
  60.         cout << "Rozwiazanie: \n";
  61.         for (int i = 0; i < N; i++)
  62.             cout << "x[" << i << "]=" << x[i] << endl;
  63.     }
  64.        
  65.     _getch();
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement