c++ - 求解具有两个未知数的两个方程组

标签 c++ math equation equation-solving

用下面两个未知数求解两个方程组:

enter image description here

a1、b1、c1、a2、b2、c2由用户自己输入。

我一直试图首先找到问题的数学解决方案,但我似乎无法走得太远..

到目前为止我尝试过的是:

  1. 从第一个方程求出y。 (b1y = c1-a1x, y = (c1-a1x)/b1)
  2. 然后我在第二个方程中替换 y,得到一个方程,其中 1 为未知数,在本例中为 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;
}

最佳答案

我们使用 Cramer's rule 求解线性系统:

int main(int argc, char** argv) {
    /* we solve the linear system
     * ax+by=e
     * cx+dy=f
     */
    if(argc != 7) {
        cerr<<"Cramer equations system: error,"
                             " we need a,b,c,d,e,f parameters.\n";
        return -1;
    }

    double a,b,e;
    double c,d,f;
    sscanf(argv[1],"%lf",&a);
    sscanf(argv[2],"%lf",&b);
    sscanf(argv[3],"%lf",&e);
    sscanf(argv[4],"%lf",&c);
    sscanf(argv[5],"%lf",&d);
    sscanf(argv[6],"%lf",&f);

    double determinant = a*d - b*c;
    if(determinant != 0) {
        double x = (e*d - b*f)/determinant;
        double y = (a*f - e*c)/determinant;
        printf("Cramer equations system: result, x = %f, y = %f\n", x, y);
    } else {
        printf("Cramer equations system: determinant is zero\n"
                "there are either no solutions or many solutions exist.\n"); 
    }
    return 0;
}

./cramer_equation_system 1 2 5 1 -1 -1

Cramer 方程组:结果,x = 1.000000,y = 2.000000

关于c++ - 求解具有两个未知数的两个方程组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19619248/

相关文章:

c++ - 不断增加物理内存 Visual C++ CryptMsgClose 和 CryptReleaseContext

c++ - 下层 std::vector<std::string>

python - 如何在 SymPy 中表示复杂平面区域?

c# - 我应该缩放我的方程式输出数据吗?

c++ - 'TraceEvents' 未定义;假设 extern 返回 int

c++ - 如何在 C++ 中创建带替换的排列?

c - 计算平方根的奇怪方法

c - 这个c程序有什么问题?调试它表明程序被击中 while (sqroot != 0);

matlab - 简单的对数曲线拟合

html - 如何在html中写方程式?