Program to find number of solutions in Quadratic Equation in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a quadratic equation of type ax2 + bx + c, where a,b and c are constants. Our task is to create a program to find number of solutions in Quadratic Equation in C++.

Problem Description − Here, we need to find the numbers of solutions for a quadratic equation that can have at max 2 solutions.

Let’s take a few examples to understand the problem,

Example 1:

Input − 3x2 + 7x + 4

Output − 2

Explanation − the two solutions of the equation are 1 and 4/3.

Example 2:

Input − x2 - 4x + 4

Output − 1

Explanation − The solution to the equation is 2.

Input − 2x2 + 2x + 2

Output − 0

Explanation: There is no solution to the equation.

Solution Approach:

To find the number of solutions, we need the nature of solutions of the quadratic equation which is found using the value of discriminant (D).

The roots of the equation are given by the formula,

= −𝑏 ± √𝑏.
D = ( (b^2) - (4*a*c) )

So, the discriminant’s value gives the number of roots of the quadratic equation.

  • If D = 0, the number of solutions is 1.

  • If D > 0, the number of solutions is 2.

  • If D < 0, the number of solutions is 0. As the value of the root of a negative number is imaginary.

Algorithm:

  • Step 1 − find the value of D, D = ((b^2) - 4*a*c).

  • Step 2 − if(D > 0), print 2 solutions

  • Step 3 − if(D = 0), print 1 solution

  • Step 4 − if(D < 0), print 0 solution

Example

#include <iostream>
using namespace std;
int checkSolution(int a, int b, int c) {
   if (((b * b) - (4 * a * c)) > 0)
      return 2;
   else if (((b * b) - (4 * a * c)) == 0)
      return 1;
   else
      return 0;
}
int main() {
   int a = 2, b = 2, c = 3;
   cout<<"The quadratic equation is "<<a<<"x^2 + "<<b<<"x +
   "<<c<<" has ";
   cout<<checkSolution(a, b, c)<<" solutions ";
   return 0;
}

Output:

The quadratic equation is 2x^2 + 2x + 3 has 0 solutions
raja
Published on 15-May-2020 13:25:59
Advertisements