【发布时间】:2013-10-27 14:36:47
【问题描述】:
求解具有以下两个未知数的两个方程组:
a1、b1、c1、a2、b2、c2由用户自己输入。
我一直在尝试先找到这个问题的数学解决方案,但我似乎无法走多远..
到目前为止我尝试过的是:
- 从第一个方程找到 y。 (b1y = c1-a1x, y = (c1-a1x)/b1)
- 然后我替换第二个方程中的 y,我得到一个方程,在这种情况下 x 为未知数。但是,我无法解方程,我得到了一些奇数/方程并停在这里。
这是正确的还是有更简单的方法可以做到这一点?
当前代码:
#include <iostream>
using namespace std;
int main()
{
int a1, b1, c1, a2, b2, c2;
cout << "Enter the values for the first equation." << endl;
cout << "Enter the value for a1" << endl;
cin >> a1;
cout << "Enter the value for b1" << endl;
cin >> b1;
cout << "Enter the value for c1" << endl;
cin >> c1;
cout << "Enter the values for the second equation." << endl;
cout << "Enter the value for a2" << endl;
cin >> a2;
cout << "Enter the value for b2" << endl;
cin >> b2;
cout << "Enter the value for c2" << endl;
cin >> c2;
cout << "Your system of equations is the following:" << endl;
cout << a1 << "x+" << b1 << "y=" << c1 << endl;
cout << a2 << "x+" << b2 << "y=" << c2 << endl;
if ((a1 * b2) - (b1 * a2) == 0){
cout << "The system has no solution." << endl;
}
else{
res_x = ((c1*b2) - (b1*c2))/((a1*b2)-(b1*a2));
res_y = ((a1*c2) - (c1*a2)) / ((a1*b2) - (b1*a2));
cout << "x=" << res_x << " y=" << res_y << endl;
}
return 0;
}
【问题讨论】:
-
在您的代码中,首先,您应该检查您的 2 个未知数系统是否有一个、无穷大或无解(计算行列式)
-
如果矩阵可逆(即 det != 0),则解决方案直接作为 2x2 矩阵 (a1,b1; a2,b2) 的逆矩阵给出。
-
你可能想检查一些库来求解方程(例如eigen)。
-
或者,如果您想知道如何获得解决方案,但不知道@AlexanderGessler 说了什么,您可以这样做:将第一个关系与
b2相乘,第二个关系与b1相乘,然后减去这两个关系。你会得到像x * (a1b2-a2b1) = c1b2 - c2b1这样的东西。现在你只需要检查a1b2 - a2b1不为0,如果不是,将最后一个关系除以它,你会得到x。如果为 0,则没有解决方案。
标签: c++ math equation equation-solving