Quadratic solver with complex roots

Jul 25, 2014 at 12:45pm
Another quadratic solver but this time with imaginary roots included. Ignoring the fact that the imaginary part gives the wrong answer (although advice would be welcome) when I build and run the program, it just prints two numbers (e.g. 16i and -12i) because the return function adds the two parts together (instead of printing one then another). It doesn't print a complex root (e.g. 2 + 3i and 2 - 3i). Would I have to split up the functions that calculate the complex roots into two separate functions that calculate the real and imaginary bits separately? Please advise.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <cmath>

using namespace std;

double RealRootOne (double a, double b, double c)
{
    double RealRootOne = ((-1*b) + sqrt((b*b) - (4*a*c))) / (2*a);
    return RealRootOne;
}

double RealRootTwo (double a, double b, double c)
{
    double RealRootTwo = ((-1*b) - sqrt((b*b) - (4*a*c))) / (2*a);
    return RealRootTwo;
}

void printRealResult (double a, double b, double c)
{
    cout << "Your results are " << RealRootOne(a, b, c) << " and " << RealRootTwo(a, b, c) << endl;
}

double ComplexRootOne (double a, double b, double c)
{
    double ComplexRealOne = (-1*b) / (2*a);
    double ComplexImOne = (-1*((b*b) - (4*a*c))) / (2*a);
    return ComplexRealOne + ComplexImOne;
}

double ComplexRootTwo (double a, double b, double c)
{
    double ComplexRealTwo = (-1*b) / (2*a);
    double ComplexImTwo = (-1*((b*b) - (4*a*c))) / (2*a);
    return ComplexRealTwo - ComplexImTwo;
}

void printComplexResult (double a, double b, double c)
{
    cout << "You're results are " << ComplexRootOne(a, b, c) << "i and " << ComplexRootTwo(a, b, c) << "i" << endl;
}

int main()
{
    cout << "Enter a, b and c for quadratic in the form ax^2 + bx + c = 0" << endl;
    double a, b, c;
    cin >> a >> b >> c;

    double disc = (b*b) - (4*a*c);

    if (disc < 0)
    {
        printComplexResult(a, b, c);
    }

    if (disc == 0)
    {
        cout << "One real and repeated root " << ((-1*b) / (2*a));
    }

    else if (disc > 0)
    {
        printRealResult(a, b, c);
    }

    return 0;
}
Jul 25, 2014 at 2:04pm
The easiest way would be to use complex numbers to return a complex number rather than a plain double. For examples, look at http://www.cplusplus.com/reference/complex/complex/ and follow the links for more details about the class.

You'll probably just want to use the 'real' root functions you have, and change it so it takes a complex value instead. After all, even when using complex numbers, the formula never changes.
Last edited on Jul 25, 2014 at 2:05pm
Jul 25, 2014 at 2:10pm
Ahh I didn't know about that! Thank you very much, more stuff to learn *rubs hands eagerly* :)
Topic archived. No new replies allowed.