// Test Case: Solve quadratic equations
// And throws variables that are either a is less than 0 or b2 is less than 0
#include <string>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <stdexcept>
void check_precondition(double a, double b, double c)
{
std::string errors;
if (a == 0)
errors += "a cannot be 0.";
else if (a < 0)
errors += "a cannot be negative.";
if (b*b <= 4 * a*c)
{
if (!errors.empty())
errors += '\n';
errors += "b squared must be greater than 4ac\n";
}
if (!errors.empty())
throw std::runtime_error(errors);
}
int main()
{
double a, b, c;
try {
std::cout << "Enter the three coefficients \n";
std::cin >> a >> b >> c;
check_precondition(a, b, c);
double discriminant = b*b - 4 * a*c;
std::cout << "The two roots are: " << ((-b + std::sqrt(discriminant)) / (2 * a));
std::cout << " and " << ((-b + std::sqrt(discriminant)) / (2 * a)) << '\n';
}
catch (std::exception& ex)
{
std::cout << "Problem encountered:\n" << ex.what() << '\n';
std::cout << "With a = " << a << ", b = " << b << ", c = " << c << '\n';
return 1;
}
}
Ly8gVGVzdCBDYXNlOiBTb2x2ZSBxdWFkcmF0aWMgZXF1YXRpb25zIAovLyBBbmQgdGhyb3dzIHZhcmlhYmxlcyB0aGF0IGFyZSBlaXRoZXIgYSBpcyBsZXNzIHRoYW4gMCBvciBiMiBpcyBsZXNzIHRoYW4gMCAKI2luY2x1ZGUgPHN0cmluZz4KI2luY2x1ZGUgPGlvc3RyZWFtPiAKI2luY2x1ZGUgPGNzdGRsaWI+IAojaW5jbHVkZSA8Y21hdGg+CiNpbmNsdWRlIDxzdGRleGNlcHQ+Cgp2b2lkIGNoZWNrX3ByZWNvbmRpdGlvbihkb3VibGUgYSwgZG91YmxlIGIsIGRvdWJsZSBjKQp7CiAgICBzdGQ6OnN0cmluZyBlcnJvcnM7CgogICAgaWYgKGEgPT0gMCkKICAgICAgICBlcnJvcnMgKz0gImEgY2Fubm90IGJlIDAuIjsKICAgIGVsc2UgaWYgKGEgPCAwKQogICAgICAgIGVycm9ycyArPSAiYSBjYW5ub3QgYmUgbmVnYXRpdmUuIjsKC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