andrew mendonca 0 Junior Poster in Training

Define a function
int getRoots(double a, double b, double c, double & s1, double & s2)

that solves a quadatic equation with coefficients a, b and c. If there are no real roots than the return value will be 0 and the values of s1 and s2 will be left as is. If there is one real solution the return value will be 1 and s1 will be set to the solution with s2 left as is. If there are two real solutions then the return value will be 2 with s1 set to the smaller solution and s2 set to the bigger solution.

You'll need to call the sqrt() function from cmath, but you don't have to #include <cmath> since that will be done in the driver.

The driver reads three floating point numbers from the console, calls your function, then outputs the solution(s), if any.

Here is my solution:

int getRoots(double a, double b, double c, double &s1, double &s2)
{
    double disc = ((b * b) - 4 * a * c);
    if(disc < 0 || a == 0)
    {
        return 0;
    }
    if((disc) == 0)
    {
        s1 = (-b) / (2 * a);
        s2 = s1;
        return 1;
    }
    if((disc) > 0)
    {
        s1 = (-b + sqrt(disc)) / (2 * a);
        s2 = (-b - sqrt(disc)) / (2 * a);
        return 2;
    }
}

Here is my output:
One solution: -0.00

Expected output I want to get:
One solution: 0.00

I'm not sure where the negative sign is coming from. Is there something I need to add or change in the quadratic formula function. I would appreciate any help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.