Description
Get the values of a, b and c (coefficients of quadratic equation) as input from the user and calculate the roots and print as the output.
Input
Enter the value of a, b and c: 1 -6 9
Output
Roots are equal
Root 1= root 2 = 3.00
C Program
#include<stdio.h>
#include<math.h>
int main() {
double a, b, c, d, root1, root2, r, i;
printf("Enter value of a, b and c: ");
scanf("%lf %lf %lf", &a, &b, &c);
d = b * b - 4 * a * c;
if (d > 0) {
printf("There are two Real Roots\n");
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
printf("root1 = %.2lf \nroot2 = %.2lf", root1, root2);
}
else if (d == 0) {
printf("Roots are equal\n");
root1 = root2 = -b / (2 * a);
printf("root1 = root2 = %.2lf;", root1);
}
else {
r = -b / (2 * a);
i = sqrt(-d) / (2 * a);
printf("No Real Roots\n");
printf("root1 = %.2lf+%.2lfi \nroot2 = %.2f-%.2fi", r, i, r, i);
}
return 0;
}
C++ Program
#include <iostream>
using namespace std;
#include<math.h>
int main() {
double a, b, c, d, root1, root2, real, imag;
cout<<"Enter value of a, b and c: ";
cin>>a>>b>>c;
d = b * b - 4 * a * c;
if (d > 0) {
cout<<"There are two Real Roots\n";
root1 = (-b + sqrt(d)) / (2 * a);
root2 = (-b - sqrt(d)) / (2 * a);
cout<<"root1 ="<<root1<<"root2 = "<<root2;
}
else if (d == 0) {
cout<<"Roots are equal\n";
root1 = root2 = -b / (2 * a);
cout<<"root1 = root2 = "<<root1;
}
else {
real = -b / (2 * a);
imag = sqrt(-d) / (2 * a);
cout<<"No Real Roots\n";
cout<<"root1 = "<<real<<"+"<<imag<<" root2 = "<<real<<"-"<<imag;
}
return 0;
}
Java
import java.util.Scanner;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
double a,b,c;
System.out.println("Enter the values for a, b and c: ");
a = sc.nextDouble();
b = sc.nextDouble();
c = sc.nextDouble();
double d = Math.pow(b,2) - 4*a*c;
if(d > 0){
System.out.println("There are two real roots");
System.out.println("Roots are " + (-b+Math.sqrt(d))/(2*a) + " and " + (-b-Math.sqrt(d))/(2*a));
}
else if (d == 0){
System.out.println("Roots are equal");
System.out.println("Roots are " + -b/(2*a));
}
else{
System.out.println("No real roots");
System.out.println("Roots are " + -b/(2*a) + "+i" +
Math.sqrt(-d)/(2*a) + " and "
+ -b/(2*a) + "-i" + Math.sqrt(-d)/(2*a));
}
}
}
Python
import math
a = int(input('Enter value for a :'))
b = int(input('Enter value for b :'))
c = int(input('Enter value for c :'))
if a == 0:
print("a cannot be zero")
else:
d = b**2 - 4 * a * c
root = math.sqrt(abs(d))
if d > 0:
print("Two Real Roots")
print((-b + root)/(2 * a))
print((-b - root)/(2 * a))
elif d == 0:
print("Roots are equal")
print(-b / (2*a))
else:
print("No Real Root")
print(- b / (2*a) , " + i", root)
print(- b / (2*a) , " - i", root)