Форум программистов, компьютерный форум, киберфорум
C++ Builder
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.82/11: Рейтинг темы: голосов - 11, средняя оценка - 4.82
1 / 1 / 0
Регистрация: 09.05.2013
Сообщений: 15

Решение системы линейных уравнений и вывод результата в файл

09.05.2013, 08:53. Показов 2256. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Всем привет.
Кто нибудь подскажите код( конечный результат ).
вот из других похожих программ элементы кода :
1)
Кликните здесь для просмотра всего текста

C++
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
100
101
102
103
104
105
106
107
#ifndef matr_in_gauseH
#define matr_in_gauseH
#include <vcl.h>
#include <iostream.h>
#include <stdlib.h>
#include <math.h>
//---------------------------------------------------------------------------
//Вывод отладочных сообщений
#define debug
class CMatrixException{
    char ne;// ne='a' Не возможно выделить память.
            // ne='+' Сложение не возможно
            // ne='-' Вычитание не возможно
            // ne='*' Уможение не возможно
            // ne='/' Division isn't possble
            // ne='d' Конвертация в тип double не возможна
            // ne='=' Невозможно прировнять матрицу
            // ne='0' Zero division matrix/double
            // ne='i' Index out of range
public:
    CMatrixException(char c){ne=c;}
    void PrintMessage(){
        cout<<"\tERROR! >>> ";
        switch(ne){
        case 'a':cout<<"Can't allocate memory"<<endl;break;
        case '+':cout<<"Addition isn't possible"<<endl;break;
        case '-':cout<<"Substruction isn't possible"<<endl;break;
        case '*':cout<<"Multiplication isn't possible"<<endl;break;
        case '/':cout<<"Division isn't possble"<<endl;break;
        case 'd':cout<<"Conversion to double isn't possible"<<endl;break;
        case '=':cout<<"Can't give to matrix"<<endl;break;
        case '0':cout<<"Zero division matrix/double"<<endl;break;
        case 'i':cout<<"Index out of range"<<endl;break;
        case 'T':cout<<"Transporent isn't possible"<<endl;break;
        case 'I':cout<<"Invertation isn't possible"<<endl;break;
        default :cout<<"Unknown error"<<endl;
        }
    }
};
class Matrix {
    int rows, cols;
    
public:
    double* p;
    //Конструктор
    Matrix(int, int);
    Matrix(int, int,double,...);
    Matrix(int, int,   int,...);
    Matrix(double);
            // Функция создает матрицу размеров 1 Х 1, m(0,0)=i
    Matrix(int);
            // Функция создает матрицу размеров 1 Х 1, m(0,0)=i
    Matrix(Matrix const &);
    //Деструктор
    ~Matrix(){if(p!=NULL)delete[]p;}
    //
    Matrix const& operator=(Matrix const&);
    //Конвертация в тип double
    operator double()const;
    //Опирация сложения
     // friend double operator+(double,Matrix const&);
    //  double operator+(double d){return d+*this;}
    //  double operator+(   int i){return double(i)+*this;}
    //  friend double operator+( int i,Matrix const&m){return double(i)+m;}
    //  Matrix const& operator+()const{return*this;}//unary +
    Matrix  operator+(Matrix const&)const;//binary +
  //    Matrix& operator+=(Matrix const&a){*this=*this+a;return*this;}
 
    //Опирация вычитания
    friend double operator-(double,Matrix const&);
    double operator-(double d)const{return -(d-*this);}
    double operator-(   int i)const{return *this-double(i);}
    friend double operator-(int i,Matrix const&m){return -(m-i);}
    Matrix  operator-(Matrix const&)const;//binary -
    Matrix& operator-=(Matrix const&a){*this=*this-a;return*this;}
    Matrix  operator-()const;//unary -
    //Опирация умножения
    Matrix& Matrix::operator*=(Matrix const&a){*this=(*this)*a;return*this;}
    Matrix  operator*(double)const;
    friend Matrix operator*(double d,Matrix const&a){return a*d;}
    Matrix& operator*=(double d){*this=*this*d;return*this;}
    Matrix operator*(Matrix const&)const;
    //Division operators
    Matrix  operator/(double d)const{
        if(d==0)throw CMatrixException('d');
        return (1./d)*(*this);
    }
    Matrix& operator/=(double d){*this=*this/d;return*this;}
    //Transposition operator
    Matrix  operator*()const;
//  friend Matrix T(Matrix const&a){return *a;}
    //Доступ к элементам матрицы
    double& Matrix::operator()(int i, int j)const;
    //Транспонирование матрицы
    Matrix T(Matrix const&a)const;
    //Обращение матрицы
    Matrix Inv(Matrix const&a)const;
    //Вывод матрицы на экран
    void Print()const;
    //Возврат кол-ва столбцов и строк матрицы
    int GetRows()const{return rows;}
    int GetCols()const{return cols;}
};
void Print(Matrix const&);
 
//---------------------------------------------------------------------------------
#endif

2)
Кликните здесь для просмотра всего текста

C++
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#pragma hdrstop
#include "matr_in_gause.h"
 
//---------------------------------------------------------------------------
#pragma package(smart_init)
//Нахождение обратной матрицы методом Гаусса
//Входные данные: double *a - исходная матрица;
//                int n     - размерность матрицы[n*n];
//    Sring name_file_save  - имя файла для записи результатов счета.
//Выходные данные: double *a - обратная матрица, вычисленная по методу Гаусса, [n*n].
int matr_inv_gause(double *a, int n)
{
  double e1, d, *b, *c, y, w, p; ;
  int i, j, k, *z;
 
  e1=1.e-6;
  d=1;
 
  z= new int[n];
  c= new double[n];
  b= new double[n];
 
 
  for(i=0; i<n; i++)
     *(z+i)=i;
 
  for(i=0; i<n; i++)
   {
    k=i;
    y=*(a+i*n+i);
    if(i+1 <= n )
      for(j=1+i; j<n; j++)
       {
        w=*(a+n*i+j);
        if(fabs(w)>fabs(y))
         {
           k=j;
           y=w;
         }
       }
    d=d*y;
//проверка на близость к вырождению матрицы  
   if(fabs(y)<e1) return 2;
   y=1./y;
   for(j=0; j<n; j++)
    {
      *(c+j)=*(a+n*j+k);
      *(a+n*j+k)=*(a+n*j+i);
      *(a+j*n+i)=-(*(c+j))*y;
      *(b+j)=*(a+i*n+j)*y;
      *(a+i*n+j)=*(b+j);
    }
   j=*(z+i);
   *(z+i)=*(z+k);
   *(z+k)=j;
   *(a+i*n+i)=y;
 
   for(k=0; k<n; k++)
    if(k != i)
      for(j=0; j<n; j++)
        if(j != i)
         *(a+k*n+j)=*(a+k*n+j)-(*(b+j))*(*(c+k));
   }
  for(i=0; i<n; i++)
    while(1)
    {
      k=*(z+i);
      if(k == i) break;
       for(j=0; j<n; j++)
        {
         w=*(a+i*n+j);
         *(a+i*n+j)=*(a+k*n+j);
         *(a+k*n+j)=w;
        }
      p=*(z+i);
      *(z+i)=*(z+k);
      *(z+k)=p;
      d=-d;
    }
 
 delete[] z;
 delete[] b;
 
 delete[] c;
 
 return 0;
}
 
 
Matrix::Matrix(int m,int n,double d,...) { 
    rows = m;  cols = n;
    double*s=&d;
    p=new double[rows*cols];
    if(p==NULL){
        throw CMatrixException('a');
    }
    for (int i=0;i<rows*cols;i++,++s)p[i]=*s;
}
Matrix::Matrix(int m,int n,  int d,...) { 
    rows = m;  cols = n;
    int*s=&d;
    p=new double[rows*cols];
    if(p==NULL){
        throw CMatrixException('a');
    }
    for (int i=0;i<rows*cols;i++,++s)p[i]=*s;
}
Matrix::Matrix(Matrix const & a) {
    rows = a.rows;
    cols = a.cols;
    p=new double[rows*cols];
    if(p==NULL){
        throw CMatrixException('a');
    }
    for (int i=0;i<rows*cols;i++)p[i]=a.p[i];
}
Matrix::Matrix(int m, int n){
    rows = m;
    cols = n;
    p=new double[rows*cols];
    if(p==NULL){
        throw CMatrixException('a');
    }
}
Matrix::Matrix(int i){
    rows = 1;
    cols = 1;
    p=new double[1];
    if(p==NULL){
        throw CMatrixException('a');
    }
    p[0]=i;
}
Matrix::Matrix(double d){
    rows = 1;
    cols = 1;
    p=new double[1];
    if(p==NULL){
        throw CMatrixException('a');
    }
    p[0]=d;
}
Matrix const& Matrix::operator=(Matrix const & a){
    if(rows!=a.rows||cols!=a.cols){
        throw CMatrixException('=');
    }
    for (int i=0;i<rows*cols;i++)p[i]=a.p[i];
    return*this;
}
Matrix::operator double()const{
    if(rows!=1||cols!=1){
        throw CMatrixException('d');
    }
    return (*this)(0,0);
}
/*
double operator+(double d,Matrix const&m){
    if(m.rows!=1||m.cols!=1){
        throw CMatrixException('+');
    }
    return d+m(0,0);
} */
Matrix Matrix::operator+(Matrix const&a)const{
    if(rows!=a.rows||cols!=a.cols){
        throw CMatrixException('+');
    }
    Matrix c(*this);
    for(int i=0;i<rows*cols;i++)c.p[i]+=a.p[i];
    return c;
}
Matrix Matrix::operator-()const{
    Matrix a(rows,cols);
    for(int i=0;i<rows*cols;i++)a.p[i]=-p[i];
    return a;
}
double operator-(double d,Matrix const&m){
    if(m.rows!=1||m.cols!=1){
        throw CMatrixException('-');
    }
    return d-m(0,0);
}
Matrix Matrix::operator-(Matrix const&a)const{
    if(rows!=a.rows||cols!=a.cols){
        throw CMatrixException('-');
    }
    Matrix c(*this);
    for(int i=0;i<rows*cols;i++)c.p[i]-=a.p[i];
    return c;
}
Matrix Matrix::operator*(Matrix const& a)const{
    if(cols!=a.rows){
        throw CMatrixException('*');
    }
    Matrix c(rows,a.cols);
    int i=0,j,k;
    for(;i<rows;++i){
        for(j=0;j<a.cols;++j){
            c(i,j)=0;
            for(k=0;k<cols;++k)c(i,j)+=(*this)(i,k)*a(k,j);
        }
    }
    return c;
}
Matrix Matrix::operator*(double d)const{
    Matrix c(*this);       
    for(int i=0;i<rows*cols;i++)c.p[i]*=d;
    return c;
}
 
double& Matrix::operator()(int i, int j)const{
    if(i>=rows || j>=cols || i<0 || j<0){
        throw CMatrixException('i');
    }
    return p[i*cols+j];
}
void Print(Matrix const& m){m.Print();}
Matrix Matrix::operator*()const{
    Matrix a(cols,rows);
    int i=0,j;
    for(;i<rows;++i)
    for(j=0;j<cols;++j)a(j,i)=(*this)(i,j);
    return a;
}
void Matrix::Print()const{
    int i=0,j;     
    cout<<endl << "Matrix>\t  ";
    for (;i<rows;i++){ ;
        for (j=0;j<cols;++j)cout<<(*this)(i,j)<<" ";
            cout<<endl <<"\t  ";
    }
    cout<<endl;
}
 
Matrix Matrix::T(Matrix const&a)const{
    if(a.rows!=a.cols){
        throw CMatrixException('T');
    }
    Matrix c(*this);
    for(int i=0;i<rows;i++)
        for(int j=0;j<cols;j++) c(i,j)=a(j,i);
 
    return c;
}
/*
int matr_inv_gause(double *a, int n)
{
  double e1, d, *b, *c, y, w, p; ;
  int i, j, k, *z;
 
  e1=1.e-6;
  d=1;
 
  z= new int[n];
  c= new double[n];
  b= new double[n];
 
 
  for(i=0; i<n; i++)
     *(z+i)=i;
 
  for(i=0; i<n; i++)
   {
    k=i;
    y=*(a+i*n+i);
    if(i+1 <= n )
      for(j=1+i; j<n; j++)
       {
        w=*(a+n*i+j);
        if(fabs(w)>fabs(y))
         {
           k=j;
           y=w;
         }
       }
    d=d*y;
//проверка на близость к вырождению матрицы  
   if(fabs(y)<e1) return 2;
   y=1./y;
   for(j=0; j<n; j++)
    {
      *(c+j)=*(a+n*j+k);
      *(a+n*j+k)=*(a+n*j+i);
      *(a+j*n+i)=-(*(c+j))*y;
      *(b+j)=*(a+i*n+j)*y;
      *(a+i*n+j)=*(b+j);
    }
   j=*(z+i);
   *(z+i)=*(z+k);
   *(z+k)=j;
   *(a+i*n+i)=y;
 
   for(k=0; k<n; k++)
    if(k != i)
      for(j=0; j<n; j++)
        if(j != i)
         *(a+k*n+j)=*(a+k*n+j)-(*(b+j))*(*(c+k));
   }
  for(i=0; i<n; i++)
    while(1)
    {
      k=*(z+i);
      if(k == i) break;
       for(j=0; j<n; j++)
        {
         w=*(a+i*n+j);
         *(a+i*n+j)=*(a+k*n+j);
         *(a+k*n+j)=w;
        }
      p=*(z+i);
      *(z+i)=*(z+k);
      *(z+k)=(int)p;
      d=-d;
    }
 
 delete[] z;
 delete[] b;
 
 delete[] c;
 
 return 0;
}
*/
Matrix Matrix::Inv(Matrix const&a)const{
    if(a.rows!=a.cols){
        throw CMatrixException('I');
    }
    if(matr_inv_gause(a.p,rows)!=0){
        throw CMatrixException('I');
    }
    return a;
}

3)
Кликните здесь для просмотра всего текста

C++
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
#include "matr_in_gause.h"
#include <stdio.h>
#include "form_help.h"
#include "form_rez.h"
#include "form_save_rez.h"
 
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma link "CSPIN"
#pragma resource "*.dfm"
 
#define N 5
double mas3[N][N];
TForm1 *Form1;
//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
        : TForm(Owner)
{
 
}
//---------------------------------------------------------------------------
void __fastcall TForm1::N1Click(TObject *Sender)
{
 //Проверка на наличие элементов в матрице
 //Если элементов нет , ф-я завершает работу
  int i, j, w, v;
  double mas1[N][N],mas2[N][N];
  TForm3* ID3 = new TForm3(this);
//задание положения Form3 на экране
  ID3->Left=179;
  ID3->Top=113;
  ID3->Height=180;
  ID3->Width=356;
 
//формирование входной матрицы a[n*n]
 a=new double[StringGrid1->ColCount*StringGrid1->ColCount];
 for(i=0; i < StringGrid1->ColCount; i++)
   for(j=0; j< StringGrid1->RowCount; j++)
     {
      if(StringGrid1->Cells[j][i]!="")
                *(a+i*StringGrid1->RowCount+j)=StrToFloat(StringGrid1->Cells[j][i]);
            else *(a+i*StringGrid1->RowCount+j)=0;
            //Если не ввести элемент, то ему присваивается 0
 
      mas1[i][j]=*(a+i*StringGrid1->RowCount+j);
     }
 
//вычисление обратнй матрицы методом Гаусса
 pr= matr_inv_gause(a,StringGrid1->RowCount);
 
//отображение результатов вычисления обратной матрицы
if(pr==0)
 {
   for(i=0; i < StringGrid2->ColCount; i++)
     for(j=0; j< StringGrid2->RowCount; j++)
       {
         StringGrid2->Cells[i][j]=FloatToStrF(*(a+j*StringGrid2->RowCount+i),ffFixed,10,4);
         mas2[i][j]=*(a+i*StringGrid2->RowCount+j);
       }
//нахождение матрицы умножения исходной на обратную.
        for(v=0; v < StringGrid3->ColCount; v++)
           {
        for(w=0; w< StringGrid3->RowCount; w++)
           {
            mas3[v][w]=0;
         for(i=0; i < StringGrid1->ColCount; i++)
          {
            mas3[v][w]=mas3[v][w]+mas1[v][i]*mas2[i][w];
          }
            StringGrid3->Cells[v][w]=FloatToStrF(mas3[v][w],ffFixed,10,4);
              StringGrid3->Cells[i][j]="";
             }
 
             }
 
  }
//анализ корректности вычисления обратной матрицы
 if(pr==2)
     {
       for(i=0; i < StringGrid2->ColCount; i++)
         for(j=0; j< StringGrid2->RowCount; j++)
           {
             StringGrid2->Cells[i][j]="";
             StringGrid3->Cells[i][j]="";
           }
       ID3->ShowModal();
     }
 ID3->Free();
 
 
 
//
 
//
 
 
 
}
//---------------------------------------------------------------------------
void __fastcall TForm1::CSpinEdit1Change(TObject *Sender)
{
int i;
 
 if (CSpinEdit1->Value > 5 ) return;
 
//pедактированиe таблицы
 StringGrid1->EditorMode=true;
 
//задание размерности входной матрицы
 StringGrid1->ColCount=CSpinEdit1->Value;
 StringGrid1->RowCount=CSpinEdit1->Value;
 
//редактированиe таблицы
 StringGrid2->EditorMode=false;
 
//задание размерности выходной матрицы
 StringGrid2->ColCount=CSpinEdit1->Value;
 StringGrid2->RowCount=CSpinEdit1->Value;
 
 
 
 
 StringGrid3->EditorMode=false;
 
//задача выходной матрицы умножения обратной на исходную
 StringGrid3->ColCount=CSpinEdit1->Value;
 StringGrid3->RowCount=CSpinEdit1->Value;
 
 
 
//очистка ячеек таблицы
 for(int i = 0; i < StringGrid1->ColCount; i++)
   for(int j = 0; j < StringGrid1->ColCount; j++)
     StringGrid2->Cells[i][j] ="";
 
 
 
 
 
 for(int i = 0; i < StringGrid1->ColCount; i++)
   for(int j = 0; j < StringGrid1->ColCount; j++)
     StringGrid3->Cells[i][j] ="";
 
 
 
     for(int v = 0; v < StringGrid3->ColCount; v++)
   for(int w= 0; w < StringGrid3->ColCount; w++)
     StringGrid3->Cells[v][w] ="";
 
 
 
//очистка ячеек таблицы
 for(int i = 0; i < StringGrid2->ColCount; i++)
   for(int j = 0; j < StringGrid2->ColCount; j++)
     StringGrid2->Cells[i][j] ="";
}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormDestroy(TObject *Sender)
{
  delete[] a;
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::FormCreate(TObject *Sender)
{ float
 x=450,y=750;
 
//задание положения MainForm (Form1) на экране
Form1->Left=23;
Form1->Top=83;
Form1->Height=x;
Form1->Width=y;
 
}
 
//---------------------------------------------------------------------------
 
 
void __fastcall TForm1::N6Click(TObject *Sender)
{
   TForm2* ID2 = new TForm2(this);
//задание положения Form2 на экране
  ID2->Left=56;
  ID2->Top=118;
  ID2->Height=264;
  ID2->Width=290;
//отображение Form2 на экране
  ID2->ShowModal();
 
  ID2->Free();
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::N2Click(TObject *Sender)
{
  FILE *h;
 
 String name_file_save;
 int i, j;
 
 TForm4* ID4 = new TForm4(this);
//задание положения Form4 на экране
  ID4->Left=189;
  ID4->Top=112;
  ID4->Height=159;
  ID4->Width=364;
 
//выбор имени файла для записи результатов счета
 SaveDialog1->Title="Введите или выберите имя файла для записи результатов счета";
 SaveDialog1->Filter= "Text. files (*.txt)|*.txt";
 
 if(SaveDialog1->Execute())
   {
     name_file_save = SaveDialog1->FileName;
   }
 
//открытие файла для записи результатов счета
  if ((h = fopen(name_file_save.c_str(),"w"))
       == NULL)
   {
      fprintf(stderr, "Cannot open input file.\n");
      return ;
   }
 
 if(pr == 0)
  {
   fprintf(h,"Результат вычисления:\n");
//запись в файл 
   for(i=0; i<StringGrid3->RowCount; i++)
    {
      for(j=0; j<StringGrid3->RowCount; j++)
       fprintf(h,"%20.12g",*(a+i*StringGrid3->RowCount+j));
       fprintf(h,"\n");
    }
  }
  if(pr==2)
    fprintf(h,"Матрица близка к вырождению.\n");
 
//закрытие файла для записи результатов счета
 fclose(h);
 
 ID4->ShowModal();
 
 ID4->Free();
 
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::N4Click(TObject *Sender)
{
Application->Terminate();
}
//---------------------------------------------------------------------------
 
 
 
 
void __fastcall TForm1::Button1Click(TObject *Sender)
{
//Проверка на наличие элементов в матрице
 //Если элементов нет , ф-я завершает работу
  int i, j, w, v;
  double mas1[N][N],mas2[N][N];
  TForm3* ID3 = new TForm3(this);
//задание положения Form3 на экране
  ID3->Left=179;
  ID3->Top=113;
  ID3->Height=180;
  ID3->Width=356;
 
//формирование входной матрицы a[n*n]
 a=new double[StringGrid1->ColCount*StringGrid1->ColCount];
 for(i=0; i < StringGrid1->ColCount; i++)
   for(j=0; j< StringGrid1->RowCount; j++)
     {
      if(StringGrid1->Cells[j][i]!="")
                *(a+i*StringGrid1->RowCount+j)=StrToFloat(StringGrid1->Cells[j][i]);
            else *(a+i*StringGrid1->RowCount+j)=0;
            //Если не ввести элемент, то ему присваивается 0
 
      mas1[i][j]=*(a+i*StringGrid1->RowCount+j);
     }
 
//вычисление обратнй матрицы методом Гаусса
 pr= matr_inv_gause(a,StringGrid1->RowCount);
 
//отображение результатов вычисления обратной матрицы
if(pr==0)
 {
   for(i=0; i < StringGrid3->ColCount; i++)
     for(j=0; j< StringGrid3->RowCount; j++)
       {
         StringGrid3->Cells[i][j]=FloatToStrF(*(a+j*StringGrid3->RowCount+i),ffFixed,10,4);
         mas2[i][j]=*(a+i*StringGrid3->RowCount+j);
       }
       /*
//нахождение матрицы умножения исходной на обратную.
        for(v=0; v < StringGrid2->ColCount; v++)
           {
        for(w=0; w< StringGrid2->RowCount; w++)
           {
            mas3[v][w]=0;
         for(i=0; i < StringGrid1->ColCount; i++)
          {
            mas3[v][w]=mas3[v][w]+mas1[v][i]*mas2[i][w];
          }
            StringGrid2->Cells[v][w]=FloatToStrF(mas3[v][w],ffFixed,10,4);
              StringGrid2->Cells[i][j]="";
             }
 
             }
          */
  }
//анализ корректности вычисления обратной матрицы
 if(pr==2)
     {
       for(i=0; i < StringGrid3->ColCount; i++)
         for(j=0; j< StringGrid3->RowCount; j++)
           {
             StringGrid3->Cells[i][j]="";
             StringGrid2->Cells[i][j]="";
           }
       ID3->ShowModal();
     }
 ID3->Free();
 
 
 
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button2Click(TObject *Sender)
{
        int i,j;
    int N_A=StringGrid1->ColCount,
            M_A=StringGrid1->RowCount;
 
        Matrix A(N_A,M_A);
 
       for(i=0; i < StringGrid1->ColCount; i++)
         for(j=0; j< StringGrid1->RowCount; j++)
         {
            if(StringGrid1->Cells[j][i]!="")
              A(i,j)= StrToFloat(StringGrid1->Cells[i][j]);
            else  A(i,j)= 0;
         }
 
       Matrix C(A.T(A));
 
 
       for(i=0; i < C.GetCols(); i++)
         for(j=0; j< C.GetRows(); j++)
         {
           StringGrid3->Cells[i][j]=FloatToStrF(C.p[i*C.GetRows()+j],ffFixed,10,4);
         }
 
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button5Click(TObject *Sender)
{
        int i,j;
    int N_A=StringGrid1->ColCount,
            M_A=StringGrid1->RowCount;
        int N_B=StringGrid2->ColCount,
            M_B=StringGrid2->RowCount;
 
        Matrix A(N_A,M_A);
        Matrix B(N_B,M_B);
 
 
 
       for(i=0; i < StringGrid1->ColCount; i++)
         for(j=0; j< StringGrid1->RowCount; j++)
         {
            if(StringGrid1->Cells[j][i]!="")
              A(i,j)= StrToFloat(StringGrid1->Cells[i][j]);
            else  A(i,j)= 0;
         }
       for(i=0; i < StringGrid2->ColCount; i++)
         for(j=0; j< StringGrid2->RowCount; j++)
         {
            if(StringGrid2->Cells[j][i]!="")
              B(i,j)= StrToFloat(StringGrid2->Cells[i][j]);
            else  B(i,j)= 0;
         }
       Matrix C(A+B);
 
       for(i=0; i < C.GetCols(); i++)
          for(j=0; j< C.GetRows(); j++)
          {
             StringGrid3->Cells[i][j]=FloatToStrF(C.p[i*C.GetRows()+j],ffFixed,10,4);
          }
 
 
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button4Click(TObject *Sender)
{
        int i,j;
    int N_A=StringGrid1->ColCount,
            M_A=StringGrid1->RowCount;
        int N_B=StringGrid2->ColCount,
            M_B=StringGrid2->RowCount;
 
        Matrix A(N_A,M_A);
        Matrix B(N_B,M_B);
 
 
 
       for(i=0; i < StringGrid1->ColCount; i++)
         for(j=0; j< StringGrid1->RowCount; j++)
         {
            if(StringGrid1->Cells[j][i]!="")
              A(i,j)= StrToFloat(StringGrid1->Cells[i][j]);
            else  A(i,j)= 0;
         }
       for(i=0; i < StringGrid2->ColCount; i++)
         for(j=0; j< StringGrid2->RowCount; j++)
         {
            if(StringGrid2->Cells[j][i]!="")
              B(i,j)= StrToFloat(StringGrid2->Cells[i][j]);
            else  B(i,j)= 0;
         }
       Matrix C(A-B);
 
       for(i=0; i < C.GetCols(); i++)
          for(j=0; j< C.GetRows(); j++)
          {
             StringGrid3->Cells[i][j]=FloatToStrF(C.p[i*C.GetRows()+j],ffFixed,10,4);
          }
        
}
//---------------------------------------------------------------------------
 
void __fastcall TForm1::Button3Click(TObject *Sender)
{
        int i,j;
    int N_A=StringGrid1->ColCount,
            M_A=StringGrid1->RowCount;
        int N_B=StringGrid2->ColCount,
            M_B=StringGrid2->RowCount;
 
        Matrix A(N_A,M_A);
        Matrix B(N_B,M_B);
 
 
 
      for(i=0; i < StringGrid1->ColCount; i++)
         for(j=0; j< StringGrid1->RowCount; j++)
         {
            if(StringGrid1->Cells[j][i]!="")
              A(i,j)= StrToFloat(StringGrid1->Cells[i][j]);
            else  A(i,j)= 0;
         }
       for(i=0; i < StringGrid2->ColCount; i++)
         for(j=0; j< StringGrid2->RowCount; j++)
         {
            if(StringGrid2->Cells[j][i]!="")
              B(i,j)= StrToFloat(StringGrid2->Cells[i][j]);
            else  B(i,j)= 0;
         }
       Matrix C(A*B);
 
       for(i=0; i < C.GetCols(); i++)
          for(j=0; j< C.GetRows(); j++)
          {
             StringGrid3->Cells[i][j]=FloatToStrF(C.p[i*C.GetRows()+j],ffFixed,10,4);
          }
 
}
//---------------------------------------------------------------------------
4)
C++
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
#ifndef matrixH //Во избежание многократного подключения 
#define matrixH //и компиляции
//Объевление структуры матрицы
typedef struct{
  double **ptr; //Двойной указатель на элементы матрицы
  int n,m; //Размеры матрицы:n-число строк,m-число чтолбцов      
} Matrix;
//Описание ввиде ссылки глобальной переменной
extern Matrix *record;
//Создание матрицы
int Creat(Matrix *);
//Создание матрицы
int CreatDop(Matrix *);
//Удаление матрицы
int Delete(Matrix *);
//Ввода матрицы
int Mscanf(Matrix);
//Вывода 
int Mprintf(Matrix);
//Вывода в файл
int Mfprintf(Matrix);
//Ввода из файла
int Mfscanf(Matrix);
//Сложения
int slogenie(Matrix,Matrix,Matrix);
//Вычитания
int vitchetanie(Matrix,Matrix,Matrix);
//Умножение матрицы на число
int YmnogNaChislo(Matrix,Matrix ,double);
//Умножение матриц
int Ymnogenie(Matrix,Matrix,Matrix);
//Транспонирование матриц
int Transponir(Matrix,Matrix);
//LU -разложение
int LU(Matrix,Matrix,Matrix);
//Вычисление определителя
int det(Matrix,double*);
//Метод Гауса
int Gays(Matrix,Matrix,Matrix);
//Нахождение обратной матрицы
int ObrMatrix(Matrix,Matrix);
//UTU разложение
int UTU(Matrix,Matrix,Matrix);
//Метод Холецкого
int Holecki(Matrix,Matrix,Matrix);
//Приведение к матрице с диаганальным преобладанием
int Diag(Matrix ,Matrix );
#endif
5)
C++
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
#ifndef matrixH
#define matrixH
typedef struct{
  double **ptr;  
  int n,m;       
} Matrix;
extern Matrix *record;
int Creat(Matrix *);
int CreatDop(Matrix *);
int Delete(Matrix *);
int Mscanf(Matrix);
int Mprintf(Matrix);
int Mfprintf(Matrix);
int Mfscanf(Matrix);
int slogenie(Matrix,Matrix,Matrix);
int vitchetanie(Matrix,Matrix,Matrix);
int YmnogNaChislo(Matrix,Matrix ,double);
int Ymnogenie(Matrix,Matrix,Matrix);
int Transponir(Matrix,Matrix);
int LU(Matrix,Matrix,Matrix);
int det(Matrix,double*);
int Gays(Matrix,Matrix,Matrix);
int ObrMatrix(Matrix,Matrix);
int UTU(Matrix,Matrix,Matrix);
int Holecki(Matrix,Matrix,Matrix);
int Diag(Matrix ,Matrix );
#endif

6)
Кликните здесь для просмотра всего текста

C++
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#include "matrix.h"
#include <conio.h>
#include <stdio.h>
int main(int argc, char *argv[])
{ 
 Matrix a,b,c;
 int ch,cm,canExit = 0;
 double f;
   while(!canExit){
     _clrscr();
     printf("\n");
     printf("                  **************** Њ…Ќћ ********************\n");
     printf("                  *        1 - ‘«®¦Ґ*ЁҐ ¬*ваЁж             *\n");
     printf("                  *        2 - ‚лзЁв**ЁҐ ¬*ваЁж            *\n");
     printf("                  *      3 - “¬*®¦Ґ*ЁҐ ¬*ваЁжл ** зЁб«®    *\n");
     printf("                  *        4 - “¬*®¦Ґ*ЁҐ ¬*ваЁж            *\n");
     printf("                  *      5 - ’а**бЇ®*Ёа®ў**ЁҐ ¬*ваЁжл      *\n");
     printf("                  *      6 - ‚лзЁб«Ёвм ®ЇаҐ¤Ґ«ЁвҐ«м        * \n");
     printf("                  *         7 - ЋЎа*в**п ¬*ваЁж*           *\n");
     printf("                  *            8 - ђҐиҐ*ЁҐ ‘‹Ђ“            *\n");
     printf("                  *             0 - ‚л室                  *\n");
     printf("                  ******************************************\n");
     printf("‚*и ўлЎ®а:");
     scanf("%d",&ch);
     printf("\n");
        switch(ch){
            case 1:{
                 _clrscr();
                Creat(&a);
                b.n=c.n=a.n;
                b.m=c.m=a.m;
                CreatDop(&b);
                             CreatDop(&c);
                Mscanf(a);
                Mscanf(b);
                             slogenie(a,b,c);
                Mprintf(c);
                Delete(&a);
                             Delete(&b);
                             Delete(&c);
                cm=1;
                printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                 while(1){
                                           if(cm==0) break;
                                       scanf("%d",&cm);
                     }
                             break;
            }
            case 2:{
                 _clrscr();
                Creat(&a);
                b.n=c.n=a.n;
                b.m=c.m=a.m;
                CreatDop(&b);
                             CreatDop(&c);
                Mscanf(a);
                Mscanf(b);
                             vitchetanie(a,b,c);
                Mprintf(c);
                Delete(&a);
                             Delete(&b);
                             Delete(&c);
                cm=1;
                printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                 while(1){
                                           if(cm==0) break;
                                        scanf("%d",&cm);
                     }
                             break;
                     }
                     case 3:{
                        _clrscr();
                     Creat(&a);
                        b.n=a.n;
                        b.m=a.m;
                        CreatDop(&b);
                               Mscanf(a);
                      printf("‚ўҐ¤ЁвҐ зЁб«®:");
                      scanf("%lf",&f);
                         YmnogNaChislo(a,b,f);
                         Mprintf(b);
                         Delete(&a);
                                Delete(&b);
                                cm=1;
                          printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                      while(1){
                                             if(cm==0) break;
                                          scanf("%d",&cm);
                                      }
                                 break;     
              }
                    case 4:{
                _clrscr();
                Creat(&a);
                             Mscanf(a);
                             printf("‚ўҐ¤ЁвҐ а*§¬Ґал ўв®а®© ¬*ваЁжл:");
                Creat(&b);
                Mscanf(b);
                c.n=a.n;
                c.m=b.m;
                             CreatDop(&c);
                Ymnogenie(a,b,c);
                Mprintf(c);
                Delete(&a);
                             Delete(&b);
                             Delete(&c);
                cm=1;
                printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                  while(1){
                                            if(cm==0) break;
                                         scanf("%d",&cm);
                     }
                             break;
             }
                    case 5:{
                _clrscr();
                Creat(&a);
                             Mscanf(a);
                             b.n=a.m;
                b.m=a.n;
                             CreatDop(&b);
                   Transponir(a,b);
                Mprintf(b);
                Delete(&a);
                             Delete(&b);                                  
                cm=1;
                printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                  while(1){
                                           if(cm==0) break;
                                      scanf("%d",&cm);
                     }
                              break;
                }
                   case 6:{
              _clrscr();
              Creat(&a);
                        Mscanf(a);
              det(a,&f);
                        printf("ЋЇаҐ¤Ґ«ЁвҐ«м: %lf",f);
                  Delete(&a);
                        cm=1;
               printf("\n0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                while(1){
                                           if(cm==0) break;
                                      scanf("%d",&cm);
                   }
                         break;
            }
                  case 7:{
            _clrscr();
            Creat(&a);
                      Mscanf(a);
                      b.n=a.n;
                b.m=a.m;
                      CreatDop(&b);
            ObrMatrix(a,b);
            Mprintf(b);
            Delete(&a);
                      Delete(&b);                                  
            cm=1;
            printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                              while(1){
                                         if(cm==0) break;
                                     scanf("%d",&cm);
                 }
                        break;
           }
                 case 8:{
            _clrscr();
                     printf("‚ўҐ¤ЁвҐ Ї®а冷Є бЁб⥬л га®ў*Ґ*Ё©:\n");
                     scanf("%d",&cm);
                     a.n=a.m=cm;
            CreatDop(&a);
                      printf("‚ўҐ¤ЁвҐ ¬*ваЁжг Є®ндЁжҐ*в®ў:\n");
                      Mscanf(a);
                      b.n=c.n=a.n;
                      b.m=c.m=1;
                CreatDop(&b);
                      printf("‚ўҐ¤ЁвҐ ўҐв®а *Ґ§*ўЁбЁ¬ле ЇҐаҐ¬Ґ**ле:\n");
            Mscanf(b);
            CreatDop(&c);
            Gays(a,b,c);
            Mprintf(c);
            Delete(&a);
                      Delete(&b);
                      Delete(&c);
             cm=1;
              printf("0-„«п ўл室* ў ¬Ґ*о:\n"); 
                                while(1){
                                             if(cm==0) break;
                                       scanf("%d",&cm);
                   }
                             break;
          }
                case 0:{
            canExit = 1;
            break;
          }
        }
  }
 return 0;
}


Ну вот и все.
Кто чем может помогите.
Спасибо всем заранее.

Добавлено через 3 минуты
Для того чтобы написать программу для решения системы линейных уравнений методом обратных матриц:
1. формула по нахождению Минора;
2. формула по нахождению Алгебраического дополнения;
3. формула по нахождению Определителя;
4. запись порядка функций в С++;
5. нахождение ошибок в программе.
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
09.05.2013, 08:53
Ответы с готовыми решениями:

Решение системы линейных уравнений
Не могу сделать прогу на С++. Кто сделает - огромное спасибо. Решить систему линейных уравнений 3x-5y+2z=2, 3x-7y+2z=0, x+5y-4z=-2

Решение системы линейных уравнений
___/sin^2x * cos x, если x&lt;0.1, x=3; y=|x+2, если 0.1&lt;x&lt;1, x&gt;4; ___\cos x /2x, в остальных случаях. ...

Решение системы линейных уравнений
Дана система линейных уравнений, их кол-во динамическое. ax+by+c=0. Даны a,b,c , найти x,y. Подкиньте пожалуйта программу.

1
1 / 1 / 0
Регистрация: 09.05.2013
Сообщений: 15
16.06.2013, 12:59  [ТС]
Решение найдено тему можно закрывать.
Всем спасибо.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
16.06.2013, 12:59
Помогаю со студенческими работами здесь

Решение системы линейных уравнений
на форуме есть решение , где матрицу приводят к треугол. виду, а можно эту задачу с оператором условия решить или нет?

Решение системы линейных уравнений
Здравствуте !!! Подскажите пожалуйста как решить большую систему линейных уравнений, которая записана в матрицу столбец. Каждому элементу...

Решение системы линейных уравнений.
Он не решает ни по одному способу, а тупо косит на Е1, в чем проблема?

Решение системы линейных уравнений
Помогите решить на Си

Решение системы линейных уравнений
Решить задачу в VBA. Программа составляется c использованием оператора IF- THEN - ELSE. Та же задача программируется с использованием...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Как я обхитрил таблицу Word
Alexander-7 21.03.2026
Когда мигает курсор у внешнего края таблицы, и нам надо перейти на новую строку, а при нажатии Enter создается новый ряд таблицы с ячейками, то мы вместо нервных нажатий Энтеров мы пишем любые буквы. . .
Krabik - рыболовный бот для WoW 3.3.5a
AmbA 21.03.2026
без регистрации и смс. Это не торговля, приложение не содержит рекламы. Выполняет свою непосредственную задачу - автоматизацию рыбалки в WoW - и ничего более. Однако если админы будут против -. . .
Программный отбор значений справочника
Maks 21.03.2026
Установка программного отбора значений справочника "Сотрудники" из модуля формы документа. В качестве фильтра для отбора служит предопределенное значение перечислений. Процедура. . .
Переходник USB-CAN-GPIO
Eddy_Em 20.03.2026
Достаточно давно на работе возникла необходимость в переходнике CAN-USB с гальваноразвязкой, оный и был разработан. Однако, все меня терзала совесть, что аж 48-ногий МК используется так тупо: просто. . .
Оттенки серого
Argus19 18.03.2026
Оттенки серого Нашёл в интернете 3 прекрасных модуля: Модуль класса открытия диалога открытия/ сохранения файла на Win32 API; Модуль класса быстрого перекодирования цветного изображения в оттенки. . .
SDL3 для Desktop (MinGW): Рисуем цветные прямоугольники с помощью рисовальщика SDL3 на Си и C++
8Observer8 17.03.2026
Содержание блога Финальные проекты на Си и на C++: finish-rectangles-sdl3-c. zip finish-rectangles-sdl3-cpp. zip
Символические и жёсткие ссылки в Linux.
algri14 15.03.2026
Существует два типа ссылок — символические и жёсткие. Ссылка в Linux — это запись в каталоге, которая может указывать либо на inode «файла-ИСТОЧНИКА», тогда это будет «жёсткая ссылка» (hard link),. . .
[Owen Logic] Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора
ФедосеевПавел 14.03.2026
Поддержание уровня воды в резервуаре количеством включённых насосов: моделирование и выбор регулятора ВВЕДЕНИЕ Выполняя задание на управление насосной группой заполнения резервуара,. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru