Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,945 questions

51,887 answers

573 users

How to find the roots of a quadratic equation in C++

2 Answers

0 votes
#include <iostream>
#include <cmath>

void quadratic_equation_roots(float a, float b, float c) {
    float discriminant = (b * b) - (4 * a * c);
 
    float root1, root2;
    if (discriminant > 0) {
        root1 = (-b + sqrt(discriminant)) / (2 * a);
        root2 = (-b - sqrt(discriminant)) / (2 * a);
        std::cout << "root1 = " << root1 << "\nroot2 = " << root2 << "\n";
    }
    else if(discriminant == 0) {
        root1 = root2 = -b / (2 * a);
        std::cout << "root1 = root2 = " << root1 << "\n";
    }
    else if(discriminant < 0) {
        float real = -b / (2 * a);
        float imaginary = sqrt(-discriminant) / (2 * a);
        std::cout << "root1 = " << real << "+" << imaginary << "i\nroot2 = " << real << "-" << imaginary << "i\n";
    }
}
 
int main(void) {
    float a = 3, b = 5, c = -9;
 
    quadratic_equation_roots(a, b, c);
    std::cout << "\n";
 
    a = 3; b = 5; c = 7;
    quadratic_equation_roots(a, b, c);
    std::cout << "\n";
 
    a = 2; b = 4; c = 2;
    quadratic_equation_roots(a, b, c);
 
    return 0;
}
 
 
 
 
/*
run:
 
root1 = 1.08876
root2 = -2.75543

root1 = -0.833333+1.28019i
root2 = -0.833333-1.28019i

root1 = root2 = -1
 
*/

 



answered Jan 11, 2022 by avibootz
edited Jan 11, 2022 by avibootz
0 votes
#include <iostream>
#include <cmath>

enum { TWO = 2 };
enum { FOUR = 4 };
enum { SQUARE = 2 };

int main() {
    float a = 3, b = 5, c = -9;

    float root1 = (-b + sqrt(pow(b, SQUARE) - FOUR * a * c)) / (TWO * a);
    float root2 = (-b - sqrt(pow(b, SQUARE) - FOUR * a * c)) / (TWO * a);

    std::cout << root1 << '\n';
    std::cout << root2;
}




/*
run:

1.08876
-2.75543

*/

 



answered Apr 23, 2022 by avibootz

Related questions

2 answers 126 views
1 answer 202 views
1 answer 191 views
1 answer 170 views
1 answer 169 views
1 answer 207 views
1 answer 141 views
...