fork(1) download
  1. // Test Case: Solve quadratic equations
  2. // And throws variables that are either a is less than 0 or b2 is less than 0
  3. #include <string>
  4. #include <iostream>
  5. #include <cstdlib>
  6. #include <cmath>
  7. #include <stdexcept>
  8.  
  9. void check_precondition(double a, double b, double c)
  10. {
  11. std::string errors;
  12.  
  13. if (a == 0)
  14. errors += "a cannot be 0.";
  15. else if (a < 0)
  16. errors += "a cannot be negative.";
  17.  
  18. if (b*b <= 4 * a*c)
  19. {
  20. if (!errors.empty())
  21. errors += '\n';
  22.  
  23. errors += "b squared must be greater than 4ac\n";
  24. }
  25.  
  26. if (!errors.empty())
  27. throw std::runtime_error(errors);
  28. }
  29.  
  30. int main()
  31. {
  32. double a, b, c;
  33.  
  34. try {
  35. std::cout << "Enter the three coefficients \n";
  36. std::cin >> a >> b >> c;
  37.  
  38. check_precondition(a, b, c);
  39.  
  40. double discriminant = b*b - 4 * a*c;
  41.  
  42. std::cout << "The two roots are: " << ((-b + std::sqrt(discriminant)) / (2 * a));
  43. std::cout << " and " << ((-b + std::sqrt(discriminant)) / (2 * a)) << '\n';
  44. }
  45.  
  46. catch (std::exception& ex)
  47. {
  48. std::cout << "Problem encountered:\n" << ex.what() << '\n';
  49. std::cout << "With a = " << a << ", b = " << b << ", c = " << c << '\n';
  50. return 1;
  51. }
  52. }
Runtime error #stdin #stdout 0s 3436KB
stdin
-1 4 -100
stdout
Enter the three coefficients 
Problem encountered:
a cannot be negative.
b squared must be greater than 4ac

With a = -1, b = 4, c = -100