C++ 程式求解含有一個變數的線性方程
任何形式的一個變數的線性方程為:aX + b = cX + d。其中,當給出 a、b、c、d 的值時,要找到 X 的值。
一個程式來解一個變數的線性方程,如下所示 −
示例
#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; } }
輸出
上述程式的輸出如下所示
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
在上述程式中,首先由使用者輸入 a、b、c 和 d 的值。然後顯示方程。如下所示 −
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;
如果 a 等於 c,並且 b 等於 d,則該方程有無窮多個解。如果 a 等於 c,則該方程錯誤。否則,將計算 X 的值並列印。如下所示 −
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; }
廣告