Friday, September 1, 2023

C++ Program that Solves a Quadratic Equation

Here's a C++ program that solves a quadratic equation of the form ax^2 + bx + c = 0 using the quadratic formula:  

#include <iostream> #include <cmath> using namespace std; int main() { double a, b, c; double discriminant, root1, root2; // Input coefficients a, b, and c cout << "Enter coefficient a: "; cin >> a; cout << "Enter coefficient b: "; cin >> b; cout << "Enter coefficient c: "; cin >> c; // Calculate the discriminant discriminant = b * b - 4 * a * c; // Check the discriminant for the nature of roots if (discriminant > 0) { // Two real and distinct roots root1 = (-b + sqrt(discriminant)) / (2 * a); root2 = (-b - sqrt(discriminant)) / (2 * a); cout << "Two real and distinct roots: " << root1 << " and " << root2 << endl; } else if (discriminant == 0) { // One real root (repeated) root1 = -b / (2 * a); cout << "One real root (repeated): " << root1 << endl; } else { // Complex roots double realPart = -b / (2 * a); double imaginaryPart = sqrt(-discriminant) / (2 * a); cout << "Complex roots: " << realPart << " + " << imaginaryPart << "i and " << realPart << " - " << imaginaryPart << "i" << endl; } return 0; }

No comments:

Post a Comment

N-point Star in Microsoft Visual Studio Console App

#include <windows.h> #include <cmath> #include <iostream> LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam,...