Introduction
Quadratic equations are a type of mathematical equation that involve a variable raised to the second power. Solving a quadratic equation can be a difficult task, but with the right knowledge and tools, it can be done quickly and easily. In this article, we will discuss how to solve a quadratic equation using C++ programming language. We will discuss the different methods of solving a quadratic equation, as well as the advantages and disadvantages of each method. We will also provide some sample code to help you get started. By the end of this article, you should have a better understanding of how to solve a quadratic equation using C++.
Solution
#include
#include
using namespace std;
int main()
{
double a, b, c;
cout << "Enter the coefficients of the quadratic equation (a, b, c): ";
cin >> a >> b >> c;
double discriminant = b*b – 4*a*c;
if (discriminant > 0)
{
double x1 = (-b + sqrt(discriminant)) / (2*a);
double x2 = (-b – sqrt(discriminant)) / (2*a);
cout << "The roots of the equation are " << x1 << " and " << x2 << endl;
}
else if (discriminant == 0)
{
double x = -b / (2*a);
cout << "The root of the equation is " << x << endl;
}
else
{
cout << "The equation has no real roots." << endl;
}
return 0;
}
One slightly unrelated suggestion I have for your a==0 error check is to use a do while statement instead of having your program close. It would look like this:
do
{
cout << "Enter a number for a: ";
cin >> a;
if (a==0)
{
cout << "Can't use 0 for a.";
}
} while (a==0);
This makes it so the user doesn’t have to restart the program if they input an invalid number. Just a suggestion.
8
solved Quadratic Equation c++ [closed]
Solved Quadratic Equation in C++
Quadratic equations are equations of the form ax2 + bx + c = 0, where a, b, and c are constants. Solving a quadratic equation in C++ is a relatively simple task, and can be done using a few lines of code.
Steps to Solve a Quadratic Equation in C++
- Input the values of a, b, and c.
- Calculate the discriminant, which is b2 – 4ac.
- If the discriminant is negative, the equation has no real solutions.
- If the discriminant is zero, the equation has one real solution.
- If the discriminant is positive, the equation has two real solutions.
- Calculate the solutions using the formula x = (-b ± √discriminant) / 2a.
Example
Let’s solve the equation 2x2 + 5x – 3 = 0.
First, we input the values of a, b, and c: a = 2, b = 5, and c = -3.
Next, we calculate the discriminant: b2 – 4ac = 52 – 4(2)(-3) = 25 + 24 = 49.
Since the discriminant is positive, the equation has two real solutions.
Finally, we calculate the solutions using the formula x = (-b ± √discriminant) / 2a: x = (-5 ± √49) / 4 = (-5 ± 7) / 4 = -1 or 2.
Therefore, the solutions to the equation 2x2 + 5x – 3 = 0 are x = -1 and x = 2.