0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 19
1

Решение СЛАУ методом Гаусса

05.05.2013, 01:04. Показов 5167. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
помогите, пожалуйста!
надо создать программу, которая считает систему линейных уравнений методом гаусса, на языке си.

заранее спасибо!
0
Лучшие ответы (1)
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
05.05.2013, 01:04
Ответы с готовыми решениями:

Решение СЛАУ методом Гаусса
Задание 7. Алгоритм Гаусса. Реализовать алгоритм решения СЛАУ методом Гаусса. Ограничения:...

Вылетает borland при решение СЛАУ методом Гаусса.
Написал программу по алгоритму(приложен к теме), но при запуске borland вылетает. :( Помогите,...

Решение СЛАУ методом гаусса с помощью матрицы вращения
помогите пожалуйста!!!!!!!!!напишите кто нибудь программу матод гаусса решения слу с помощью...

Решение СЛАУ методом Гаусса для 3 уравнений с 2-мя неизвестными
Нужно создать функцию для решения СЛАУ методом Гаусса для 3 уравнений с 2-мя неизвестными ...

6
6 / 6 / 2
Регистрация: 04.05.2013
Сообщений: 27
05.05.2013, 01:08 2
Цитата Сообщение от Альбина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
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
//HOWTO solve system of linear equations
//ax=b
//where a[N][N] is square matrix,
//b[N] and x[N] are columns
 
//data are stored in input text file:
 
//input file format:
//a_11 a_12 a_13... a_1N b_1
//a_21 a_22 a_23... a_2N b_2
//...
//a_N1 a_N2 a_N3... a_NN b_N
 
#include <stdio.h>
#include <process.h>
float **a, *b, *x;
int N;
char filename[256];
FILE* InFile=NULL;
void count_num_lines(){
   //count number of lines in input file - number of equations
   int nelf=0;       //non empty line flag
   do{
       nelf = 0;
       while(fgetc(InFile)!='\n' && !feof(InFile)) nelf=1;
       if(nelf) N++;
   }while(!feof(InFile));
}
 
void freematrix(){
   //free memory for matrixes
   int i;
   for(i=0; i<N; i++){
       delete [] a[i];
   }
   delete [] a;
   delete [] b;
   delete [] x;
}
 
void allocmatrix(){
   //allocate memory for matrixes
   int i,j;
   x = new float[N];
   b = new float[N];
   a = new float*[N];
   if(x==NULL || b==NULL || a==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       exit(-1);
   }
   for(i=0; i<N; i++){
       a[i] = new float[N];
       if(a[i]==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       }
   }
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       a[i][j]=0;
       }
       b[i]=0;
       x[i]=0;
   }
}
 
void readmatrix(){
   int i=0,j=0;
   //read matrixes a and b from input file
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       fscanf(InFile, "%f", &a[i][j]);
       }
       fscanf(InFile, "%f", &b[i]);
   }
}
 
void printmatrix(){
   //print matrix "a"
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       printf(" %+f*X%d", a[i][j], j);
       }
       printf(" =%f\n", b[i]);
   }
}
 
void testsolve(){
   //test that ax=b
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       float s = 0;
       for(j=0; j<N; j++){
       s += a[i][j]*x[j];
       }
       printf("%f\t%f\n", s, b[i]);
   }
}
void printresult(){
   int i=0;
   printf("\n");
   printf("Result\n");
   for(i=0; i<N; i++){
       printf("X%d = %f\n", i, x[i]);
   }
}
void diagonal(){
   int i, j, k;
   float temp=0;
   for(i=0; i<N; i++){
       if(a[i][i]==0){
       for(j=0; j<N; j++){
           if(j==i) continue;
           if(a[j][i] !=0 && a[i][j]!=0){
           for(k=0; k<N; k++){
               temp = a[j][k];
               a[j][k] = a[i][k];
               a[i][k] = temp;
           }
           temp = b[j];
           b[j] = b[i];
           b[i] = temp;
           break;
           }
       }
       }
   }
}
void cls(){
   for(int i=0; i<25; i++) printf("\n");
}
void main(){
   int i=0,j=0, k=0;
   cls();
   do{
       printf("\nInput filename: ");
       scanf("%s", filename);
       InFile = fopen(filename, "rt");
   }while(InFile==NULL);
   count_num_lines();
   allocmatrix();
   rewind(InFile);
   //read data from file
   readmatrix();
   //check if there are 0 on main diagonal and exchange rows in that case
   diagonal();
   fclose(InFile);
   printmatrix();
   //process rows
   for(k=0; k<N; k++){
       for(i=k+1; i<N; i++){
       if(a[k][k]==0){
           printf("\nSolution is not exist.\n");
           return;
       }
       float M = a[i][k] / a[k][k];
       for(j=k; j<N; j++){
           a[i][j] -= M * a[k][j];
       }
       b[i] -= M*b[k];
       }
   }
   printmatrix();
   for(i=N-1; i>=0; i--){
       float s = 0;
       for(j = i; j<N; j++){
       s = s+a[i][j]*x[j];
       }
       x[i] = (b[i] - s) / a[i][i];
   }
 
   InFile = fopen(filename, "rt");
   readmatrix();
   fclose(InFile);
   printmatrix();
   testsolve();
   printresult();
   freematrix();
}
1
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 19
05.05.2013, 10:15  [ТС] 3
а чтоб информация шла не с файла, а ввод сразу с клавиатуры
0
6 / 6 / 2
Регистрация: 04.05.2013
Сообщений: 27
05.05.2013, 15:13 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
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
//HOWTO solve system of linear equations
//ax=b
//where a[N][N] is square matrix,
//b[N] and x[N] are columns
 
//input data format:
//a_11 a_12 a_13... a_1N b_1
//a_21 a_22 a_23... a_2N b_2
//...
//a_N1 a_N2 a_N3... a_NN b_N
 
#include <stdio.h>
#include <process.h>
float **a, *b, *x;
int N;
 
void freematrix(){
   //free memory for matrixes
   int i;
   for(i=0; i<N; i++){
       delete [] a[i];
   }
   delete [] a;
   delete [] b;
   delete [] x;
}
 
void allocmatrix(){
   //allocate memory for matrixes
   int i,j;
   x = new float[N];
   b = new float[N];
   a = new float*[N];
   if(x==NULL || b==NULL || a==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       exit(-1);
   }
   for(i=0; i<N; i++){
       a[i] = new float[N];
       if(a[i]==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       }
   }
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       a[i][j]=0;
       }
       b[i]=0;
       x[i]=0;
   }
}
 
void readmatrix(){
   int i=0,j=0;
   //read matrixes a and b from input data
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       scanf("%f", &a[i][j]);
       }
       scanf("%f", &b[i]);
   }
}
 
void printmatrix(){
   //print matrix "a"
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       printf(" %+f*X%d", a[i][j], j);
       }
       printf(" =%f\n", b[i]);
   }
}
 
void printresult(){
   int i=0;
   printf("\n");
   printf("Result\n");
   for(i=0; i<N; i++){
       printf("X%d = %f\n", i, x[i]);
   }
}
 
void diagonal(){
   int i, j, k;
   float temp=0;
   for(i=0; i<N; i++){
       if(a[i][i]==0){
       for(j=0; j<N; j++){
           if(j==i) continue;
           if(a[j][i] !=0 && a[i][j]!=0){
           for(k=0; k<N; k++){
               temp = a[j][k];
               a[j][k] = a[i][k];
               a[i][k] = temp;
           }
           temp = b[j];
           b[j] = b[i];
           b[i] = temp;
           break;
           }
       }
       }
   }
}
 
void cls(){
   for(int i=0; i<25; i++) printf("\n");
}
 
void main(){
   int i=0, j=0, k=0;
   cls();
   printf("\nInput number of equations: ");
   scanf("%d", &N);
   allocmatrix();
   //read data
   printf("\nInput data according to the description in the begining of this cpp file:\n");
   readmatrix();
   //check if there are 0 on main diagonal and exchange rows in that case
   diagonal();
   printmatrix();
   //process rows
   for(k=0; k<N; k++){
       for(i=k+1; i<N; i++){
       if(a[k][k]==0){
           printf("\nSolution is not exist.\n");
           return;
       }
       float M = a[i][k] / a[k][k];
       for(j=k; j<N; j++){
           a[i][j] -= M * a[k][j];
       }
       b[i] -= M*b[k];
       }
   }
   printmatrix();
   for(i=N-1; i>=0; i--){
       float s = 0;
       for(j = i; j<N; j++){
       s = s+a[i][j]*x[j];
       }
       x[i] = (b[i] - s) / a[i][i];
   }
   printresult();
   freematrix();
}
1
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 19
24.05.2013, 17:02  [ТС] 5
а можно еще так сделать, чтоб оба кода выводили результат на экран и в файл, пожалуйста.
0
6 / 6 / 2
Регистрация: 04.05.2013
Сообщений: 27
26.05.2013, 23:40 6
Цитата Сообщение от Альбина1
а можно еще так сделать, чтоб оба кода выводили результат на экран и в файл, пожалуйста.

Вот первый вариант с вводом из файла. Ответ записывает в файл(answer.txt), и пишет на экран.
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
//HOWTO solve system of linear equations
//ax=b
//where a[N][N] is square matrix,
//b[N] and x[N] are columns
 
//data are stored in input text file:
 
//input file format:
//a_11 a_12 a_13... a_1N b_1
//a_21 a_22 a_23... a_2N b_2
//...
//a_N1 a_N2 a_N3... a_NN b_N
 
#include <stdio.h>
#include <process.h>
float **a, *b, *x;
int N;
char filename[256];
FILE* InFile=NULL;
FILE* InFile1=NULL;
void count_num_lines(){
   //count number of lines in input file - number of equations
   int nelf=0;       //non empty line flag
   do{
       nelf = 0;
       while(fgetc(InFile)!='\n' && !feof(InFile)) nelf=1;
       if(nelf) N++;
   }while(!feof(InFile));
}
 
void freematrix(){
   //free memory for matrixes
   int i;
   for(i=0; i<N; i++){
       delete [] a[i];
   }
   delete [] a;
   delete [] b;
   delete [] x;
}
 
void allocmatrix(){
   //allocate memory for matrixes
   int i,j;
   x = new float[N];
   b = new float[N];
   a = new float*[N];
   if(x==NULL || b==NULL || a==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       exit(-1);
   }
   for(i=0; i<N; i++){
       a[i] = new float[N];
       if(a[i]==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       }
   }
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       a[i][j]=0;
       }
       b[i]=0;
       x[i]=0;
   }
}
 
void readmatrix(){
   int i=0,j=0;
   //read matrixes a and b from input file
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       fscanf(InFile, "%f", &a[i][j]);
       }
       fscanf(InFile, "%f", &b[i]);
   }
}
 
void printmatrix(){
   //print matrix "a"
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       printf(" %+f*X%d", a[i][j], j);
       }
       printf(" =%f\n", b[i]);
   }
}
 
void testsolve(){
   //test that ax=b
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       float s = 0;
       for(j=0; j<N; j++){
       s += a[i][j]*x[j];
       }
       printf("%f\t%f\n", s, b[i]);
   }
}
void printresult(){
   int i=0;
   printf("\n");
   printf("Result\n");
   for(i=0; i<N; i++){
       printf("X%d = %f\n", i, x[i]);
   }
}
void printresult1(){
   int i=0;
   fprintf(InFile1, "Result\n");
   for(i=0; i<N; i++){
       fprintf(InFile1, "X%d = %f\n", i, x[i]);
   }
}
void diagonal(){
   int i, j, k;
   float temp=0;
   for(i=0; i<N; i++){
       if(a[i][i]==0){
       for(j=0; j<N; j++){
           if(j==i) continue;
           if(a[j][i] !=0 && a[i][j]!=0){
           for(k=0; k<N; k++){
               temp = a[j][k];
               a[j][k] = a[i][k];
               a[i][k] = temp;
           }
           temp = b[j];
           b[j] = b[i];
           b[i] = temp;
           break;
           }
       }
       }
   }
}
void cls(){
   for(int i=0; i<25; i++) printf("\n");
}
void main(){
   int i=0,j=0, k=0;
   cls();
   do{
       printf("\nInput filename: ");
       scanf("%s", filename);
       InFile = fopen(filename, "rt");
   }while(InFile==NULL);
   count_num_lines();
   allocmatrix();
   rewind(InFile);
   //read data from file
   readmatrix();
   //check if there are 0 on main diagonal and exchange rows in that case
   diagonal();
   fclose(InFile);
   printmatrix();
   //process rows
   for(k=0; k<N; k++){
       for(i=k+1; i<N; i++){
       if(a[k][k]==0){
           printf("\nSolution is not exist.\n");
           return;
       }
       float M = a[i][k] / a[k][k];
       for(j=k; j<N; j++){
           a[i][j] -= M * a[k][j];
       }
       b[i] -= M*b[k];
       }
   }
   printmatrix();
   for(i=N-1; i>=0; i--){
       float s = 0;
       for(j = i; j<N; j++){
       s = s+a[i][j]*x[j];
       }
       x[i] = (b[i] - s) / a[i][i];
   }
 
   InFile = fopen(filename, "rt");
   readmatrix();
   fclose(InFile);
   printmatrix();
   testsolve();
   printresult();
   InFile1 = fopen("answer.txt", "w");
   printresult1();
   fclose(InFile1);
   freematrix();
}
Вот второй вариант с вводом с клавиатуры. Ответ записывает в файл(answer.txt), и пишет на экран.
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
//HOWTO solve system of linear equations
//ax=b
//where a[N][N] is square matrix,
//b[N] and x[N] are columns
 
//input data format:
//a_11 a_12 a_13... a_1N b_1
//a_21 a_22 a_23... a_2N b_2
//...
//a_N1 a_N2 a_N3... a_NN b_N
 
#include <stdio.h>
#include <process.h>
float **a, *b, *x;
int N;
FILE* InFile=NULL;
 
void freematrix(){
   //free memory for matrixes
   int i;
   for(i=0; i<N; i++){
       delete [] a[i];
   }
   delete [] a;
   delete [] b;
   delete [] x;
}
 
void allocmatrix(){
   //allocate memory for matrixes
   int i,j;
   x = new float[N];
   b = new float[N];
   a = new float*[N];
   if(x==NULL || b==NULL || a==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       exit(-1);
   }
   for(i=0; i<N; i++){
       a[i] = new float[N];
       if(a[i]==NULL){
       printf("\nNot enough memory to allocate for %d equations.\n", N);
       }
   }
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       a[i][j]=0;
       }
       b[i]=0;
       x[i]=0;
   }
}
 
void readmatrix(){
   int i=0,j=0;
   //read matrixes a and b from input data
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       scanf("%f", &a[i][j]);
       }
       scanf("%f", &b[i]);
   }
}
 
void printmatrix(){
   //print matrix "a"
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       printf(" %+f*X%d", a[i][j], j);
       }
       printf(" =%f\n", b[i]);
   }
}
 
void printresult(){
   int i=0;
   printf("\n");
   printf("Result\n");
   for(i=0; i<N; i++){
       printf("X%d = %f\n", i, x[i]);
   }
}
 
void printresult1(){
   int i=0;
   fprintf(InFile, "Result\n");
   for(i=0; i<N; i++){
       fprintf(InFile, "X%d = %f\n", i, x[i]);
   }
}
 
void diagonal(){
   int i, j, k;
   float temp=0;
   for(i=0; i<N; i++){
       if(a[i][i]==0){
       for(j=0; j<N; j++){
           if(j==i) continue;
           if(a[j][i] !=0 && a[i][j]!=0){
           for(k=0; k<N; k++){
               temp = a[j][k];
               a[j][k] = a[i][k];
               a[i][k] = temp;
           }
           temp = b[j];
           b[j] = b[i];
           b[i] = temp;
           break;
           }
       }
       }
   }
}
 
void cls(){
   for(int i=0; i<25; i++) printf("\n");
}
 
void main(){
   int i=0, j=0, k=0;
   cls();
   printf("\nInput number of equations: ");
   scanf("%d", &N);
   allocmatrix();
   //read data
   printf("\nInput data according to the description in the begining of this cpp file:\n");
   readmatrix();
   //check if there are 0 on main diagonal and exchange rows in that case
   diagonal();
   printmatrix();
   //process rows
   for(k=0; k<N; k++){
       for(i=k+1; i<N; i++){
       if(a[k][k]==0){
           printf("\nSolution is not exist.\n");
           return;
       }
       float M = a[i][k] / a[k][k];
       for(j=k; j<N; j++){
           a[i][j] -= M * a[k][j];
       }
       b[i] -= M*b[k];
       }
   }
   printmatrix();
   for(i=N-1; i>=0; i--){
       float s = 0;
       for(j = i; j<N; j++){
       s = s+a[i][j]*x[j];
       }
       x[i] = (b[i] - s) / a[i][i];
   }
   printresult();
   InFile = fopen("answer.txt", "w");
   printresult1();
   fclose(InFile);
   freematrix();
}
1
0 / 0 / 0
Регистрация: 02.12.2012
Сообщений: 19
03.06.2013, 22:44  [ТС] 7
помогите, пожалуйста! не могу найти причину. когда данные идут с файла-все хорошо работает, когда с клавиатуры-подсчет не верный. Там в printmatrix появляется много каких-то нулей.
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
#include <conio.h> 
#include <stdio.h>
#include <process.h>
float **a, *b, *x;
int N;
char filename[256];
FILE* InFile=NULL;
FILE* InFile1=NULL;
void count_num_lines(){
      //розраховувати кількість рядків у вхідному файлі - число рівнянь
   int nelf=0;       //non empty line flag
   do{
       nelf = 0;
       while(fgetc(InFile)!='\n' && !feof(InFile)) nelf=1;
       if(nelf) N++;
   }while(!feof(InFile));
}
 
void freematrix(){
   // звільнена память масивів
   int i;
   for(i=0; i<N; i++){
       delete [] a[i];
   }
   delete [] a;
   delete [] b;
   delete [] x;
}
 void menu(){
 printf("___________________________________________\n");
  printf("********|-----------MENU----------|********\n");
  printf("*******************************************\n");
  printf("********natusnit klavishy 1 abo 2**********");
  printf("\n**|1-dani z klaviatyru|                  \n");
  printf("* |2-dani z fajly|                        *\n");
  printf("* --------------------------------------- *\n");
  printf("*-----------------------------------------*\n");
  printf("*-----------------------------------------*\n");
  printf("* slidyjte nastypnum vkazivkam            *\n");
  printf("* virno vvodte dani, inakshe programa     *\n");
  printf("* prupunut roboty                         *\n");
  printf("******************************************\n");
}
void choice()
{int q;
void keyboard();
void file();
scanf_s ("%d",&q);
switch (q)
{case 1:
keyboard(); break;
case 2:
    file(); break;
default:
    printf ("ne virna forma");}
 
}
void allocmatrix(){
      //виділити память для матриць
   int i,j;
   x = new float[N];// масив невідомих
   b = new float[N]; //масив вільних членів
   a = new float*[N];  // масив коефіц при невідомих
   if(x==NULL || b==NULL || a==NULL){   //якщо NULL - виділити память не вдалось
              printf("\n ne vucta4ae pamjati %d.\n", N);
       exit(-1);
   }
   for(i=0; i<N; i++){
       a[i] = new float[N];  //виділення памяті
       if(a[i]==NULL){
       printf("\n ne vucta4ae pamjati %d.\n", N);
       }
   }
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){  //занулює масиви
       a[i][j]=0;
       }
       b[i]=0;
       x[i]=0;
   }
}
 
void readmatrix(){
   int i=0,j=0;
      //зчитування а і в з вхідних даних
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       fscanf(InFile, "%fl", &a[i][j]);
       }
       fscanf(InFile, "%fl", &b[i]);
   }
}
 
void printmatrix(){
         //введення коефіцієнтів "a" і вільних членів "в"
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       printf(" %+f*X%d", a[i][j], j);
       }
       printf(" =%f\n", b[i]);
   }
}
 
 
void testsolve(){
   //test that ax=b
   int i=0,j=0;
   printf("\n");
   for(i=0; i<N; i++){
       float s = 0;
       for(j=0; j<N; j++){
       s += a[i][j]*x[j];
       }
       printf("%f\t%f\n", s, b[i]);
   }
}
void printresult(){   //виведення рехультатів
   int i=0;
   printf("\n");
   printf("Result\n");
   for(i=0; i<N; i++){
       printf("X%d = %f\n", i, x[i]);
   }
}
void printresult1(){ //результат записується в файл
   int i=0;
   fprintf(InFile1, "Result\n");
   for(i=0; i<N; i++){
       fprintf(InFile1, "X%d = %f\n", i, x[i]);
   }
}
void diagonal(){
   int i, j, k;
   float temp=0;
   for(i=0; i<N; i++){  //цикл по рядках матриці
       if(a[i][i]==0){  //якщо по головні діагоналі 0
       for(j=0; j<N; j++){  //цикл по елементах матриці
           if(j==i) continue;//якщо j та i рівні, новий виток циклу
           if(a[j][i] !=0 && a[i][j]!=0){  //якщо елементи метриці, симетричні відносно головної діагоналі не нульові
           for(k=0; k<N; k++){  //то міняються місцями відповідні рядки
               temp = a[j][k];
               a[j][k] = a[i][k]; //заміна елементів основної матриці
               a[i][k] = temp;
           }
           temp = b[j];
           b[j] = b[i];  //заміна вільних членів
           b[i] = temp;
           break;
 
           }
       }
       }
   }
}
void keyboard()
{ int i=0, j=0, k=0;
   
   printf("\n vvestu kilkict rivnjan: ");
   scanf("%d", &N);
   printf("\nVvestu koeficientu: \n");
allocmatrix();
//   int i=0,j=0;
      //зчитування а і в з вхідних даних
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       scanf("%d", &a[i][j]);
       }
       scanf("%d", &b[i]);
   }
}
 
  void file()
      {
    int i=0,j=0, k=0;
   do{
       printf("\n vvestu imja fajly : ");
       scanf("%s", filename);
       InFile = fopen(filename, "rt");
   }
   while(InFile==NULL);
   count_num_lines();
 
   allocmatrix();
   rewind(InFile);
   //read data from file
 
//     int i=0,j=0;
      //зчитування а і в з вхідних даних
   for(i=0; i<N; i++){
       for(j=0; j<N; j++){
       fscanf(InFile, "%fl", &a[i][j]);
       }
       fscanf(InFile, "%fl", &b[i]);
   }
   fclose(InFile);
  }
  void main(){
     menu();
     choice();
      //readmatrix();
      //file();
   
   diagonal();//перевіряємо чи є нулі на головній діагоналі і у такому випадку міняємо рядки місцями
   
   printmatrix();
   int i, k, j;
  //обробка рядків
   for(k=0; k<N; k++){  //зводимо до ступінчатого вигляду, цикл проходить 
       for(i=k+1; i<N; i++){  //внутрішній цикл починається з наступного рядку
       if(a[k][k]==0){  //якщо на головній діагоналі 0 - розвязку не має
                      printf("\n rozvjazky nemae.\n");
           return;
       }
       float M = a[i][k] / a[k][k];  // операції з рядками (n+1)-((n+1)/n)*n  2/1, коефіцієнт * 1, 2-коефіцієнт * М - коефіцієнт, який перетворить
       for(j=k; j<N; j++){
           a[i][j] -= M * a[k][j];  //перетворення відповідного рядка коефіцієнтів, в якому утворився нуль
       }
 
       b[i] -= M*b[k];
       }
   }
   printmatrix();
   for(int i=N-1; i>=0; i--){ //обхід відбувається у зворотному порядку, починаючи з останнього невідомого 
       float s = 0;
       for(int j = i; j<N; j++){
       s = s+a[i][j]*x[j];  //сума добутку коефіцієнтів і розвязків
       }
       x[i] = (b[i] - s) / a[i][i];  //знаходження невідомого (вільний член+сума)/коефіцієнт біля невідомого
   }
 
   printmatrix();
   testsolve();
   printresult();
   InFile1 = fopen("result.txt", "w");
   printresult1();
   fclose(InFile1);
   freematrix();
     _getch();
 
    return;
 
   
}
0
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
03.06.2013, 22:44
Помогаю со студенческими работами здесь

Написать программу которая находит решение СЛАУ методом Гаусса
Помогите найти ошибку в коде. Нужно написать программу которая находит решение СЛАУ методом...

Решение СЛАУ методом Зейделя (Гаусса-Зейделя) с заданной матрицей
ребята, помогите написать на си, решение слау методом Зейделя(Гаусса-Зейделя) с заданной матрицей

Реализация алгоритма решения СЛАУ методом Гаусса
Попрошу помочь в реализации алгоритма решения СЛАУ методом Гаусса на языке С (НЕ C++!). Заранее...

Разработать программу для решения СЛАУ методом Гаусса
Разработать программу для решения СЛАУ методом Гаусса есть код, но во первых он не работает во...

Ошибка в программе для решения СЛАУ методом Гаусса
Здравствуйте помогите пожалуйста! Не могу найти ошибку в программе :( Алгоритм такой: среди...

МНК (метод наименьших квадратов) в базисе факториальных многочленов. СЛАУ методом Гаусса
Все верно? #include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;math.h&gt; #include &lt;stdlib.h&gt; using...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2023, CyberForum.ru