Skip to content

Instantly share code, notes, and snippets.

@kimitoboku
Created June 25, 2015 07:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimitoboku/2d8159c4f6e12dbc31da to your computer and use it in GitHub Desktop.
Save kimitoboku/2d8159c4f6e12dbc31da to your computer and use it in GitHub Desktop.
逆行列
#include<iostream>
#include<iomanip>
int main(int argc, char *argv[]){
int n;
double input;
std::cout << "n次の正方行列? n:";
std::cin >> n;
double a[n][n];
double e[n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
std::cout << i+1 << "行" << j+1 << "列目:";
std::cin >> input;
a[i][j] = input;
if(i==j){
e[i][j]=1.0;
}else{
e[i][j]=0.0;
}
}
}
double buf;
for(int i=0;i<n;i++){
buf = 1/a[i][i];
for(int j=0;j<n;j++){
a[i][j] = a[i][j] * buf;
e[i][j] = e[i][j] * buf;
}
for(int j=0;j<n;j++){
if(i!=j){
buf = a[j][i];
for(int k=0;k<n;k++){
a[j][k] = a[j][k] - a[i][k]*buf;
e[j][k] = e[j][k] - e[i][k]*buf;
}
}
}
}
std::cout << std::fixed << std::setprecision(4);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
std::cout << e[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment