Skip to content

Instantly share code, notes, and snippets.

@kimitoboku
Last active August 29, 2015 14:23
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/0b6584dffab7fd4caba6 to your computer and use it in GitHub Desktop.
Save kimitoboku/0b6584dffab7fd4caba6 to your computer and use it in GitHub Desktop.
n元連立方程式
#include<iostream>
#include<iomanip>
int main(int argc, char *argv[]){
int n;
double input;
std::cout << "n次元の連立方程式:";
std::cin >> n;
double a[n][n];
double e[n][n];
std::cout << "Ax=Bとする時の行列Aを入力して下さい" << std::endl;
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 b[n];
double x[n];
std::cout << "Ax=Bとする時の行列Bを入力して下さい" << std::endl;
for(int i=0;i<n;i++){
std::cout << i+1 << "行目:";
std::cin >> input;
b[i] = input;
x[i] = 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;
}
}
}
}
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
x[i] += e[i][j] * b[j];
}
}
for(int i=0;i<n;i++){
std::cout << x[i] << " ";
}
std::cout << std::endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment