fork download
  1. #include <iostream>
  2. #include <sstream>
  3. #include <cmath>
  4.  
  5. void quadratic( double a, double b , double c , std::string &x1 , std::string &x2 )
  6. {
  7. // ( -b +/- sqrt( b*b - ( 4 * a * c ) ) ) / ( 2 * a )
  8. //if discriminant is negative it is imaginary
  9. double discriminant = b * b - ( 4 * a * c );
  10. double denominator = 2 * a;
  11. bool imaginary = false;
  12.  
  13. if( discriminant < 0 )
  14. {
  15. imaginary = true;
  16. discriminant = -discriminant;
  17. }
  18. std::stringstream ss;
  19. if( imaginary )
  20. {
  21. ss << -b / denominator;
  22. x1 = ss.str() + '+';
  23. x2 = ss.str() + '-';
  24. ss.str("");
  25. ss.clear();
  26. ss << sqrt( discriminant ) / denominator;
  27. x1 += ss.str() + 'i';
  28. x2 += ss.str() + 'i';
  29. }
  30. else
  31. {
  32. ss << ( -b + sqrt( discriminant ) ) / denominator;
  33. x1 = ss.str();
  34. ss.str("");
  35. ss.clear();
  36. ss << ( -b - sqrt( discriminant ) ) / denominator ;
  37. x2 = ss.str();
  38. }
  39. }
  40.  
  41. int main()
  42. {
  43. double a = 1.0;
  44. double b = -11.0;
  45. double c = 36.5;
  46.  
  47. std::string x1 = "";
  48. std::string x2 = "";
  49.  
  50. quadratic( a , b , c , x1 , x2 );
  51.  
  52. std::cout << x1 << std::endl;
  53. std::cout << x2 << std::endl;
  54.  
  55. quadratic( -1 , 10 , 5 , x1 , x2 );
  56.  
  57. std::cout << x1 << std::endl;
  58. std::cout << x2 << std::endl;
  59. return(0);
  60. }
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
5.5+2.5i
5.5-2.5i
-0.477226
10.4772