連立方程式を解くサンプルプログラム
ax+by=e
cx+dy=f
を解くプログラム.
ここでは,3x-y=3とx-2y=-4の解(x=2,y=3)を求めている.
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
double a, b, c, d, e, f;
double x, y;
a = 3;
b = -1;
c = 1;
d = -2;
e = 3;
f = -4;
double det = a * d - b * c;
if (det == 0.0) {
cout << "det = 0" << std::endl;
} else {
x = (d * e - b * f) / det;
y = (-c * e + a * f) / det;
cout << "x = " << x << ", y = " << y << std::endl;
}
return 0;
}
※ cmath は math.h をC++で使うときのヘッダファイル.