# Cpp - Write program to compute solutions of quadratic equations

## Requirements

The formula for calculating quadratic equations is shown opposite.

• Arguments: The coefficients a, b, c and two pointers to both solutions.
• Returns: false, if no real solution is available, otherwise true.

Test the function by outputting the quadratic equations on the opposite page and their solutions.

## Hint

The quadratic equation: a*x*x + b*x + c = 0 has real solutions:

```x1 = (-b + square root of (b - 4ac)) / 2a
x2 = (-b - square root of (b - 4ac)) / 2a
```

If the discriminant satisfies: b*b - 4ac >= 0

If the value of (b*b - 4ac) is negative, no real solution exists.

Test values

```Quadratic Equation          Solutions

2x*x  - 2x - 1.5 = 0          x1  = 1.5,  x2  = -0.5
x*x  - 6x + 9 = 0             x1  = 3.0,  x2  = 3.0
2x*x  + 2 = 0                 none
```

## Demo

```// Defines and calls the function quadEquation(),
// which computes the solutions of quadratic equations
//            a*x*x + b*x + c = 0
// The equation and its solutions are printed by

#include <iostream>
#include <iomanip>
#include <string>
#include <cmath>              // For the square root sqrt()
using namespace std;

// Computing solutions:
bool quadEquation( double a, double b, double c,
double* x1Ptr, double* x2Ptr);

// Printing the equation and its solutions:
void printQuadEquation( double a, double b, double c);

int main() // w w  w .  ja v a2s .  c  o  m
{

return 0;
}
// Prints the equation and its solutions:
void printQuadEquation( double a, double b, double c)
{
double x1 = 0.0, x2 = 0.0;           // For solutions

cout  << "\nThe quadratic equation:\n\t "
<< a << "*x*x + " << b << "*x + " <<  c << " = 0"
<< endl;

if( quadEquation( a, b, c, &x1, &x2) )
{
cout << "has real solutions:"
<< "\n\t x1 = " << x1
<< "\n\t x2 = " << x2 << endl;
}
else
cout << "has no real solutions!" << endl;

cout << "\nGo on with return. \n\n";
cin.get();
}

bool quadEquation( double a, double b, double c,
double* x1Ptr, double* x2Ptr)
// Computes the solutions of the quadratic equation:
//            a*x*x + b*x + c = 0
// Stores the solutions in the variables to which
// x1Ptr and x2Ptr point.
// Returns: true, if a solution exists,
//                otherwise false.
{
bool return_flag = false;

double help = b*b - 4*a*c;

if( help >= 0)            // There are real solutions.
{
help = sqrt( help);

*x1Ptr = (-b + help) / (2*a);
*x2Ptr = (-b - help) / (2*a);

return_flag = true;
}
return return_flag;
}
```