Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ giải phương trình bậc nhất một ẩn


Phương trình bậc nhất một ẩn có dạng aX + b = cX + d. Cần tìm X khi biết a, b, c, d.

Ví dụ

#include <iostream>
using namespace std;

int main() {
    float a, b, c, d, X;
    cout << "The form of the linear equation in one variable is: aX + b = cX + d" << endl;
    cout << "Enter the values of a, b, c, d: " << endl;
    cin >> a >> b >> c >> d;
    cout << "The equation is " << a << "X + " << b << " = " << c << "X + " << d << endl;
    if (a == c && b == d)
        cout << "There are infinite solutions possible for this equation" << endl;
    else if (a == c)
        cout << "This is a wrong equation" << endl;
    else {
        X = (d - b) / (a - c);
        cout << "The value of X = " << X << endl;
    }
    return 0;
}

Kết quả

The form of the linear equation in one variable is: aX + b = cX + d
Enter the values of a, b, c, d:
The equation is 5X + 3 = 4X + 9
The value of X = 6

Nhập hệ số và hiển thị phương trình:

cout << "The form of the linear equation in one variable is: aX + b = cX + d" << endl;
cout << "Enter the values of a, b, c, d: " << endl;
cin >> a >> b >> c >> d;
cout << "The equation is " << a << "X + " << b << " = " << c << "X + " << d << endl;

Xử lý các trường hợp đặc biệt:

if (a == c && b == d)
    cout << "There are infinite solutions possible for this equation" << endl;
else if (a == c)
    cout << "This is a wrong equation" << endl;
else {
    X = (d - b) / (a - c);
    cout << "The value of X = " << X << endl;
}