Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3. #include <vector>
  4.  
  5. double computeDiscriminant(double a, double b, double c) {
  6. return pow(b, 2) - (4 * a * c);
  7. }
  8.  
  9. double applyQuadraticFormula(double a, double b, double c, int sign) {
  10. double numerator = -b + (sign * sqrt(computeDiscriminant(a, b, c)));
  11. double denominator = 2 * a;
  12. return numerator / denominator;
  13. }
  14.  
  15. std::vector<double> solveQuadraticEquation( double a, double b, double c ){
  16. if ( a == 0.0 ) throw std::runtime_error("a must not be 0");
  17. std::vector<double> results;
  18. double discriminant = computeDiscriminant(a, b, c);
  19. if ( discriminant >= 0.0 ){
  20. results.push_back(applyQuadraticFormula(a,b,c,1) );
  21. if ( discriminant > 0.0){
  22. results.push_back(applyQuadraticFormula(a,b,c,-1) );
  23. }
  24. }
  25. return results;
  26. }
  27.  
  28. double readDoubleFromCin(){
  29. double result;
  30. std::cin >> result;
  31. if ( std::cin.fail() ) throw std::runtime_error("could not read number from cin");
  32. return result;
  33. }
  34.  
  35. int main(){
  36. try{
  37. double a, b, c;
  38.  
  39. std::cout << "Please enter the values of a, b, and c: ";
  40.  
  41. a = readDoubleFromCin();
  42. b = readDoubleFromCin();
  43. c = readDoubleFromCin();
  44.  
  45. std::vector<double> solutions = solveQuadraticEquation( a, b, c );
  46.  
  47. switch ( solutions.size() ){
  48. case 0:
  49. std::cout << "There is no solution." << std::endl;
  50. break;
  51. case 1:
  52. std::cout << "There is 1 solution." << std::endl;
  53. std::cout << "The solution is: " << solutions.at(0) << std::endl;
  54. break;
  55. case 2:
  56. std::cout << "There are 2 solutions." << std::endl;
  57. std::cout << "The solutions are: " << solutions.at(0)
  58. << " and " << solutions.at(1) << std::endl;
  59. break;
  60. }
  61. }
  62. catch(std::runtime_error& e){
  63. std::cout << "an error happened: " << e.what() << std::endl;
  64. }
  65.  
  66. return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement