Here in this program we will compute the 2 possible roots of a quadratic equation a quadratic equation is represented as ax 2 + bx + c. a = coefficient of x 2 b= coefficient of x c= constant C++:
#include<iostream.h> #include< conio.h> #include<stdio.h> #include<math.h> void main() { clrscr(); float r_1,r_2,a,b,c,d,ip,rp; cout<<"Enter the coefficient of x^2; "; cin>>a; cout<<"Enter the coefficient of x: "; cin>>b; cout<<"Enter constant; "; cin>>c; d = (b*b)-(4*a*c); if(d>0) { cout<<"\n Real and Distinct roots\n" ; r_1 =(-b+sqrt(d))/(2*a); r_2 =(-b-sqrt(d))/(2*a); cout<<"Roots are: "<<r_1<<" and "<<r_2; } else if(d==0) { cout<<"\n Real and Equal roots"; r_1= r_2= -b/(2*c); cout<<"\nThe roots are: "<< r_1<<" and "<<r_2; } else { cout<<"Complex and Imaginary roots\n"; rp = -b/(2*a); ip=sqrt(-d)/(2*a); cout<<"The roots are: "<<rp<<" and "<<ip; } getch(); }
Output:
Enter the coefficient of x^2: 5 Enter the coefficient of x: 6 Enter constant: 1 Real and Distinct roots Roots are: -0.2 and -1.0
Python:
import math a= float(input("Enter the coefficient of x^2: ")) b= float(input("Enter the coefficient of x: ")) c= float(input("Enter constant: ")) d= (b**2)-(4*a*c) if d>0: print("Real and Distinct roots") r_1= (-b+math.sqrt(d))/(2*a) r_2 =(-b-math.sqrt(d))/(2*a) print("Roots are:",r_1,"and",r_2) else: if d==0: print("Real and Equal roots") r_2= -b/(2*c) r_1=r_2 print("Roots are:",r_1,"and",r_2) else: print("Complex and Imaginary roots") rp =-b/(2*a) ip = math.sqrt(-d)/(2*a) print("Roots are:",rp,"and",ip)
Output:
Enter the coefficient of x^2: 5 Enter the coefficient of x: 6 Enter constant: 1 Real and Distinct roots Roots are: -0.2 and -1.0
People are also reading:
- WAP in C++ and Python to calculate 3X3 Matrix multiplication
- Most Asked Pattern Programs in C
- WAP in C++ and python to convert temperature from Fahrenheit to Celsius and vice-versa
- Binary Search in C
- WAP in C to check whether the number is a Palindrome number or not
- WAP in C++ & Python to Calculate Compound Interest
- Python Program to Find LCM
- WAP to find quotient and remainder of two numbers
- Perfect Number in C
- Python Program to Print all Prime Numbers in an Interval
Leave a Comment on this Post