I am very new to C++, and am trying to create a pair of functions that will report two possible real solutions to a quadratic equation. I am also trying to enter a message into these functions that will display in lieu of a solution if no real solution exists.
The functions correctly report real solutions, but when a non-real solution appears, the program will return "The two possible real solutions to this problem are nan and nan," and my error message ("There is no real solution to that quadratic equation. Please enter a different set of numbers") does not show up in the terminal at all.
Here is my code. Thank you in advance for your help!
#include <iostream>
#include "std_lib_facilities.h" // from a Github page by Bjarne Stroustrup that corresponds with the Programming: Practices and Principles book. Note that I am learning this on my own; it is not for homework.
#include <cmath>
double quafo1 (double a, double b, double c)
{
if ((sqrt((b*b)-(4*a*c))) < 0)
{
cout << ("There is no real solution to that quadratic equation. Please enter a different set of numbers;/n");
}
else {
double x1 = ((b * -1) + sqrt((b * b) - (4 * a * c))) / (2 * a);
return x1;
}
}
double quafo2 (double a, double b, double c)
{
if ((sqrt((b*b)-(4*a*c))) < 0)
cout << ("There is no solution to that quadratic equation. Please enter a different set of numbers;");
else {
double x2 = ((b * -1) - sqrt((b * b) - (4 * a * c))) / (2 * a);
return x2;
}
}
double a;
double b;
double c;
int main()
{
cout << "This program will solve a quadratic equation as long as one or more real solutions are possible. Please enter values for a, b, and c (separated by spaces and followed by enter, e.g. 3 5 4), after which both possible answers for x will be provided. Please note that a cannot equal 0.\n";
while (cin >> a >> b >> c)
{
cout << "The two possible real solutions to this problem are " << quafo1(a, b, c) << " and " << quafo2(a,b,c) << ".\n";
}
}