Sorry if this seems a bit basic, I'm pretty new to all this etc. I'm trying to write a programme which can read in real coefficients of a 2nd order polynomial (ax^2 + bx + c = 0) and produce its roots in terms of x1 and x2.. this is what I have so far:
Code:
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<math.h>
main ()
{
int ia,ib,ic;
float a, b, c;
float x1, x2;
float s1;
cout<<"Polynomial task"<<endl;
cout<<" "<<endl;
cout<<"x1 = -b/2a + sqrt((b^2/4a^2) - c/a)"<<endl;
cout<<"x2 = -b/2a - sqrt((b^2/4a^2) - c/a)"<<endl;
cout<<" "<<endl;
cout<<"Choose a value for a:"<<endl;
cin>>ia;
if (ia==0)
{
cout<<"Division by 0 is not possible, please choose another value."<<endl;
getch();
return(0);
}
cout<<"Choose a value for b:"<<endl;
cin>>ib;
cout<<"Choose a value for c:"<<endl;
cin>>ic;
a = (float)ia;
b = (float)ib;
c = (float)ic;
s1 = sqrt( ( (ib^2) / (4 * (ia^2)) ) - (c/a) );
if (s1 < 0)
{
cout<<"No possible solution for these values"<<endl;
getch();
return(0);
}
x1 = -(b / (2*a) ) + s1;
cout<<" "<<endl;
cout<<"x1 ="<<endl;
cout<<x1<<endl;
x2 = -(b / (2*a) ) - s1;
cout<<" "<<endl;
cout<<"x2 ="<<endl;
cout<<x2<<endl;
getch();
return(0);
}
The values for a, b and c I have are:
5, 3, -1
-3, 27, 0.5
5, 0, 0
5, 50, 0
1, 4, 4
0, 4, 4
0, 0, 0
0, 2.74, 0
However the values I'm getting when I plug in these coefficients for x1 and x2 are way off the mark. I'm not really sure where I'm going wrong. Any help is appreciated.