Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <cmath>
- #include <vector>
- double computeDiscriminant(double a, double b, double c) {
- return pow(b, 2) - (4 * a * c);
- }
- double applyQuadraticFormula(double a, double b, double c, int sign) {
- double numerator = -b + (sign * sqrt(computeDiscriminant(a, b, c)));
- double denominator = 2 * a;
- return numerator / denominator;
- }
- std::vector<double> solveQuadraticEquation( double a, double b, double c ){
- if ( a == 0.0 ) throw std::runtime_error("a must not be 0");
- std::vector<double> results;
- double discriminant = computeDiscriminant(a, b, c);
- if ( discriminant >= 0.0 ){
- results.push_back(applyQuadraticFormula(a,b,c,1) );
- if ( discriminant > 0.0){
- results.push_back(applyQuadraticFormula(a,b,c,-1) );
- }
- }
- return results;
- }
- double readDoubleFromCin(){
- double result;
- std::cin >> result;
- if ( std::cin.fail() ) throw std::runtime_error("could not read number from cin");
- return result;
- }
- int main(){
- try{
- double a, b, c;
- std::cout << "Please enter the values of a, b, and c: ";
- a = readDoubleFromCin();
- b = readDoubleFromCin();
- c = readDoubleFromCin();
- std::vector<double> solutions = solveQuadraticEquation( a, b, c );
- switch ( solutions.size() ){
- case 0:
- std::cout << "There is no solution." << std::endl;
- break;
- case 1:
- std::cout << "There is 1 solution." << std::endl;
- std::cout << "The solution is: " << solutions.at(0) << std::endl;
- break;
- case 2:
- std::cout << "There are 2 solutions." << std::endl;
- std::cout << "The solutions are: " << solutions.at(0)
- << " and " << solutions.at(1) << std::endl;
- break;
- }
- }
- catch(std::runtime_error& e){
- std::cout << "an error happened: " << e.what() << std::endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement