Finding the root of a "real" quadratic equation

We were given an assignment yesterday to have it submitted today,i did the solution to it only to find it working abnormally. The question was to find the root of a simple quadratic equation(the quoted "real" is just to scare the heck outta us"
here's my code which runs fine,no error but the results looks like 1.#ID,kinda weird

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<iostream>
#include<math.h>
using namespace std;
int main(){
    signed int a,b,c,e;
    float d,f,g;
    cout<<"Enter the value of a: ";
    cin>>a;
    cout<<"B here: ";cin>>b;
    cout<<"C here: ";cin>>c;
    d=sqrt((b*b)-(4*a*c));
    e=(-1*b);
    f=(e+d)/(2*a);
    g=(e-d)/(2*a);
    cout<<"The root of the quadratic equation is "<<f
    <<" and "<<g<<endl;
    system("pause");
    return 0;
}
It works fine for me...
Enter the value of a: 2
B here: 5
C here: -2
The root of the quadratic equation is 0.350781 and -2.85078
Press any key to continue . . .

The only thing you might want to do is check to make sure the roots are real, or you'll get NaNs in your output.
Oh, and #include <cstdlib> because you're using system("pause").
(or, preferably, use something other than system() )
Agreed, it works fine for simple equations with real roots, what input are you testing?
@longdoublemain...thnx for testing,I'll include the header file,see if it works
@naraku thnx i used Any! Starting with any random variable entered thru' your keyboard.But when i tried something like say,a=1,b=5,c=6(just for example),what i get is -1.#1D and 1.#1N which is the weird part for me. For emphasis sakes,i use DevC++4.9.9
Last edited on
With that input I get
Enter the value of a: 1
B here: 5
C here: 6
The root of the quadratic equation is -2 and -3
Press any key to continue . . .
Perhaps an issue with DevC++ which is quite outdated.
Try a=9,b=1 and c=9
Enter the value of a: 9
B here: 1
C here: 9
The root of the quadratic equation is nan and nan
Press any key to continue . . .


You didn't check for nonreal roots (b^2 - 4ac must be >= 0).
Yeah right but please how do i go about that?a code segment please?
After you have your a, b, and c from the user, just check if b^2 - 4ac < 0, and if it is, print an error message and quit.
1
2
3
4
5
if (b*b - 4*a*c < 0)
    cout << "Nonreal roots!" << endl;
else
{
    // calculate roots here... 
You've been so helpful buddy,appreciate it alot.Thnx
Topic archived. No new replies allowed.