Reputation: 229
Given below is a C++ program to find the value of x and y in simultaneous linear equations.
using namespace std;
#include<iostream>
int main()
{
int m,n,a,b,c,p,q,r,x,y;
cout<<"For the system of equation ax+by=c and px+qy=r,";
cout<<"\nGive the value of a,b,c,p,q and r respectively:";
cin>>a>>b>>c>>p>>q>>r;
m=q-((p*b)/a);
n=r-((p*c)/a);
if(q==0)
cout<<"No solution";
else
y=(n/m);
x=(c-(b*y))/a;
cout<<"x= "<<x<<" & y= "<<y<<"\n";
return 0;
}
The problem with this program is that when I am giving the inputs as
3 1 13 1 6 -7 I get x=4 & y=-1
That is
For the system of equation ax+by=c and px+qy=r,
Give the value of a,b,c,p,q and r respectively:3 1 13 1 6 -7
x= 4 & y= -1
Now again I am giving the same input but in a little different way
1 6 -7 3 1 13 I get x=5 & y=-2
That is
For the system of equation ax+by=c and px+qy=r,
Give the value of a,b,c,p,q and r respectively:1 6 -7 3 1 13
x= 5 & y= -2
The right answer is x= 5 & y= -2.
Now the question is that, we have two equations and we have to solve for x and y. Here it will not matter that by which method we solve these equation because by any method we will get the value of x and y as 5 and -2 respectively.
So for same two equations why I am getting two different solutions.
Kindly help me in understanding the problem in my program.
Upvotes: 0
Views: 291
Reputation: 418
You are using the int
type to store your variables. In the first case, a
is 3, which leads to fractions in your equations which are cut off because int
cannot store them.
In the second example, a
is 1, so no fractions occur and your program calculates the correct answer.
Use float
or double
.
Upvotes: 2