本文实例讲述了C++实现的求解多元一次方程。分享给大家供大家参考,具体如下:
注:这里计算的是n*n的等距矩阵,代码如下:
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
|
#include<iostream>
#include<math.h>
#include<fstream>
#include<stdlib.h>
using namespace std;
void print( double (*pArray)[4], int iWidth, int iHigh);
void main(){
int n,m;
double a[3][4] = {
{100, 10, 1, 10},
{400, 20, 1, 20},
{900, 30, 1, 10},
}; //第四列是增广矩阵
int i,j;
n = 3;
cout<< "输入方程组介数:" ;
cout<<n<<endl;
cout<< "输入增广矩阵:" <<endl;
for (i = 0; i < n; i++){
for (j = 0; j < n + 1;j++){
cout<<a[i][j]<< " " ;
}
cout<<endl;
}
for (j = 0; j < n; j++){
double max = 0;
double imax = 0;
for (i = j; i < n; i++){
if (imax < fabs (a[i][j])){
imax = fabs (a[i][j]);
max = a[i][j]; //得到各行中所在列最大元素
m = i;
}
}
if ( fabs (a[j][j]) != max) {
double b = 0;
for ( int k = j;k < n + 1; k++){
b = a[j][k];
a[j][k] = a[m][k];
a[m][k] = b;
}
}
print(a, 3, 4);
for ( int r = j;r < n + 1;r++){
a[j][r] = a[j][r] / max; //让该行的所在列除以所在列的第一个元素,目的是让首元素为1
}
print(a, 3, 4);
for (i = j + 1;i < n; i++){
double c = a[i][j];
if (c == 0) continue ;
for ( int s = j;s < n + 1;s++){
double tempdata = a[i][s];
a[i][s] = a[i][s] - a[j][s] * c; //前后行数相减,使下一行或者上一行的首元素为0
print(a, 3, 4);
}
print(a, 3, 4);
}
print(a, 3, 4);
}
for (i = n - 2; i >= 0; i--){
for (j = i + 1;j < n; j++){
double tempData = a[i][j];
double data1 = a[i][n];
double data2 = a[j][n];
a[i][n] = a[i][n] - a[j][n] * a[i][j];
print(a, 3, 4);
}
}
print(a, 3, 4);
cout<< "方程组的解是:" <<endl;
for ( int k = 0; k < n; k++){
cout<< "x" <<k<< " = " <<a[k][n]<<endl;
}
}
void print( double (*pArray)[4], int iWidth, int iHigh) {
std::cout<< "Array: " << "\n" ;
for ( int i = 0; i < iWidth; i++){
for ( int j = 0; j < iHigh;j++){
cout<<pArray[i][j]<< " " ;
}
cout<<endl;
}
}
|
PS:这里再为大家推荐几款计算工具供大家进一步参考借鉴:
科学计算器在线使用_高级计算器在线计算:https://tool.zzvips.com/t/jsq/
希望本文所述对大家C++程序设计有所帮助。
原文链接:http://blog.csdn.net/ganpengjin1/article/details/22959923