C++ Online Compiler
Example: Quadratic Equation Roots using Class in C++
C
C++
C#
Java
Python
PHP
main.cpp
STDIN
Run
// Quadratic Equation Roots using Class #include <iostream> // For input/output operations #include <cmath> // For sqrt() and pow() functions #include <iomanip> // For setprecision() using namespace std; // Define a class to represent a Quadratic Equation class QuadraticEquation { private: double a, b, c; // Coefficients of the quadratic equation public: // Constructor to initialize the coefficients QuadraticEquation(double coeffA, double coeffB, double coeffC) { a = coeffA; b = coeffB; c = coeffC; } // Method to calculate and display the roots void findRoots() { if (a == 0) { cout << "Invalid quadratic equation: 'a' cannot be zero." << endl; return; } double discriminant = b * b - 4 * a * c; double root1, root2; cout << fixed << setprecision(2); // Format output to 2 decimal places if (discriminant > 0) { root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); cout << "Roots are real and distinct." << endl; cout << "Root 1 = " << root1 << endl; cout << "Root 2 = " << root2 << endl; } else if (discriminant == 0) { root1 = root2 = -b / (2 * a); cout << "Roots are real and same." << endl; cout << "Root 1 = Root 2 = " << root1 << endl; } else { // discriminant < 0 double realPart = -b / (2 * a); double imaginaryPart = sqrt(-discriminant) / (2 * a); cout << "Roots are complex and distinct." << endl; cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl; cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl; } } }; int main() { // Step 1: Declare variables for coefficients double coeff_a, coeff_b, coeff_c; // Step 2: Prompt user for input cout << "Enter coefficient a: "; cin >> coeff_a; cout << "Enter coefficient b: "; cin >> coeff_b; cout << "Enter coefficient c: "; cin >> coeff_c; // Step 3: Create an object of QuadraticEquation class QuadraticEquation eq(coeff_a, coeff_b, coeff_c); // Step 4: Call the findRoots method to calculate and display roots eq.findRoots(); return 0; }
Output
Clear
ADVERTISEMENTS