Quadratic Equation Solver Gaming Project in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#include <iostream> #include <cmath> #include <stdexcept> // Function to calculate the roots of the quadratic equation void solveQuadraticEquation(double a, double b, double c) { // Check if the equation is actually quadratic if (a == 0) { throw std::invalid_argument("Coefficient 'a' cannot be zero for a quadratic equation."); } // Calculate the discriminant double discriminant = b * b - 4 * a * c; std::cout << "Solving equation: " << a << "x^2 + " << b << "x + " << c << " = 0\n"; // Check the discriminant value if (discriminant > 0) { // Two distinct real roots double root1 = (-b + std::sqrt(discriminant)) / (2 * a); double root2 = (-b - std::sqrt(discriminant)) / (2 * a); std::cout << "Roots are real and different.\n"; std::cout << "Root 1: " << root1 << "\n"; std::cout << "Root 2: " << root2 << "\n"; } else if (discriminant == 0) { // One real root (repeated) double root = -b / (2 * a); std::cout << "Roots are real and the same.\n"; std::cout << "Root: " << root << "\n"; } else { // Complex roots double realPart = -b / (2 * a); double imaginaryPart = std::sqrt(-discriminant) / (2 * a); std::cout << "Roots are complex and different.\n"; std::cout << "Root 1: " << realPart << " + " << imaginaryPart << "i\n"; std::cout << "Root 2: " << realPart << " - " << imaginaryPart << "i\n"; } } int main() { // Example coefficients for the quadratic equation double a = 1.0, b = -3.0, c = 2.0; try { solveQuadraticEquation(a, b, c); } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << "\n"; } return 0; } |
Explanation solveQuadraticEquation Function: Parameters: Takes three coefficients a, b, and c representing the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0. Discriminant Calculation: Computes the discriminant using the formula b2−4acb^2 – 4acb2−4ac. The discriminant determines the nature of the roots: If the discriminant is positive, the equation has two distinct real roots. If …