zoukankan      html  css  js  c++  java
  • 高斯消元

    Q 求 n 元 1 次线性方程组的解

    1 。 先写出矩阵的增广矩阵

    2 。 进行初等行变换,将左侧的矩阵变成单位矩阵,此时最右侧即是整个方程组的解

    #include <bits/stdc++.h>
    using namespace std;
    const double eps = 1e-8;
    
    double a[10][10], del;
    int n;
    
    int solve(){
    	for(int i = 1; i <= n; i++){
    		int k = i;
    		for(int j = i+1; j <= n; j++){
    			if (fabs(a[j][i]) > fabs(a[k][i])) k = j;
    		}
    		if (fabs(del = a[k][i]) < eps) return 0;
    		for(int j = i; j <= n+1; j++) swap(a[i][j], a[k][j]);
    		for(int j = i; j <= n+1; j++) a[i][j] /= del;	
    		for(int j = 1; j <= n; j++) {
    			if (j == i) continue;
    			del = a[j][i];
    			for(int f = i; f <= n+1; f++) a[j][f] -= del*a[i][f]; 
    		}
    	}
    	return 1;
    }
    
    int main () {
    	int t;
    	
    	cin >> t;
    	while(t--){
    		n = 2;
    		memset(a, 0, sizeof(a));
    		for(int i = 1; i <= n+1; i++){
    			for(int j = 1; j <= n; j++){
    				scanf("%lf", &a[j][i]);
    			}
    		}
    			
    		int sign = solve();
    		if (!sign) cout << "NO" << endl;
    		else {
    			for(int i = 1; i <= n; i++) printf("%.2lf
    ", a[i][n+1]);
    		}
    		
    //		for(int i = 1; i <= n; i++){
    //    		for(int j = 1; j <= n+1; j++) printf("%.2lf%c", a[i][j], j==n+1?'
    ':' ');
    //		}
    	}
    		
    	
    	return 0;
    }
    
    /*
    1
    1 1
    3 1
    4 2
    */
    
  • 相关阅读:
    for each/in
    对象与结构体的区别
    php与构造函数和析构函数
    回顾PHP之类与对象
    回顾PHP之数组篇
    正则个人总结
    echo 与print_r??
    六月学习与感想
    晚到的五月博客
    java复习
  • 原文地址:https://www.cnblogs.com/ccut-ry/p/10278924.html
Copyright © 2011-2022 走看看