Last active
August 29, 2015 14:23
-
-
Save kimitoboku/0b6584dffab7fd4caba6 to your computer and use it in GitHub Desktop.
n元連立方程式
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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