本文共 859 字,大约阅读时间需要 2 分钟。
#includeconst int maxn = 15 + 1;double a[maxn][maxn], b[maxn];int main(){ int n; freopen("gauss.txt", "r", stdin); //读入数据 scanf("%d", &n); for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) scanf("%lf", &a[i][j]); scanf("%lf", &b[i]); } for(int k = 1; k <= n - 1; k++) //消元过程 for(int i = k + 1; i <= n; i++) { double Mik = a[i][k] / a[k][k]; for(int j = k + 1; j <= n; j++) a[i][j] -= Mik * a[k][j]; b[i] -= Mik * b[k]; } b[n] /= a[n][n]; //回代过程 for(int i = n - 1; i >= 1; i--) { double sum = 0; for(int j = i + 1; j <= n; j++) sum += a[i][j] * b[j]; b[i] = (b[i] - sum) / a[i][i]; } for(int i = 1; i <= n; i++) printf("x%d = %f\n", i, b[i]); //小优化b[]->x[] return 0;}
数据文件
实验结果